File: mptWine.cpp

package info (click to toggle)
libopenmpt 0.4.3-1%2Bdeb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 7,724 kB
  • sloc: cpp: 99,820; sh: 4,503; ansic: 3,449; makefile: 480
file content (760 lines) | stat: -rw-r--r-- 21,463 bytes parent folder | download | duplicates (2)
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
/*
 * mptWine.cpp
 * -----------
 * Purpose: Wine stuff.
 * Notes  : (currently none)
 * Authors: OpenMPT Devs
 * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
 */


#include "stdafx.h"
#include "mptWine.h"

#include "mptOS.h"
#include "mptFileIO.h"

#include <deque>
#include <map>

#if MPT_OS_WINDOWS
#include <windows.h>
#endif


OPENMPT_NAMESPACE_BEGIN


#if defined(MODPLUG_TRACKER) && MPT_OS_WINDOWS


namespace mpt
{
namespace Wine
{



Context::Context(mpt::Wine::VersionContext versionContext)
	: m_VersionContext(versionContext)
	, wine_get_dos_file_name(nullptr)
	, wine_get_unix_file_name(nullptr)
{
	if(!mpt::Windows::IsWine())
	{
		throw mpt::Wine::Exception("Wine not detected.");
	}
	if(!m_VersionContext.Version().IsValid())
	{
		throw mpt::Wine::Exception("Unknown Wine version detected.");
	}
	m_Kernel32 = mpt::Library(mpt::LibraryPath::FullPath(P_("kernel32.dll")));
	if(!m_Kernel32.IsValid())
	{
		throw mpt::Wine::Exception("Could not load Wine kernel32.dll.");
	}
	if(!m_Kernel32.Bind(wine_get_unix_file_name, "wine_get_unix_file_name"))
	{
		throw mpt::Wine::Exception("Could not bind Wine kernel32.dll:wine_get_unix_file_name.");
	}
	if(!m_Kernel32.Bind(wine_get_dos_file_name, "wine_get_dos_file_name"))
	{
		throw mpt::Wine::Exception("Could not bind Wine kernel32.dll:wine_get_dos_file_name.");
	}
	{
		std::string out;
		std::string err;
		try
		{
			if(ExecutePosixShellCommand("uname -m", out, err) != 0)
			{
				throw mpt::Wine::Exception("Wine 'uname -m' failed.");
			}
			if(!err.empty())
			{
				throw mpt::Wine::Exception("Wine 'uname -m' failed.");
			}
			out = mpt::String::Trim(out, std::string("\r\n"));
			m_Uname_m = out;
		} catch(const std::exception &)
		{
			m_Uname_m = std::string();
		}
	}
	try
	{
		m_HOME = GetPosixEnvVar("HOME");
	} catch(const std::exception &)
	{
		m_HOME = std::string();
	}
	try
	{
		m_XDG_DATA_HOME = GetPosixEnvVar("XDG_DATA_HOME");
		if(m_XDG_DATA_HOME.empty())
		{
			m_XDG_DATA_HOME = m_HOME + "/.local/share";
		}
	} catch(const std::exception &)
	{
		m_XDG_DATA_HOME = std::string();
	}
	try
	{
		m_XDG_CACHE_HOME = GetPosixEnvVar("XDG_CACHE_HOME");
		if(m_XDG_CACHE_HOME.empty())
		{
			m_XDG_CACHE_HOME = m_HOME + "/.cache";
		}
	} catch(const std::exception &)
	{
		m_XDG_CACHE_HOME = std::string();
	}
	try
	{
		m_XDG_CONFIG_HOME = GetPosixEnvVar("XDG_CONFIG_HOME");
		if(m_XDG_CONFIG_HOME.empty())
		{
			m_XDG_CONFIG_HOME = m_HOME + "/.config";
		}
	} catch(const std::exception &)
	{
		m_XDG_CONFIG_HOME = std::string();
	}
}


std::string Context::PathToPosix(mpt::PathString windowsPath)
{
	std::string result;
	if(windowsPath.empty())
	{
		return result;
	}
	if(windowsPath.Length() >= 32000)
	{
		throw mpt::Wine::Exception("Path too long.");
	}
	LPSTR tmp = nullptr;
	tmp = wine_get_unix_file_name(windowsPath.ToWide().c_str());
	if(!tmp)
	{
		throw mpt::Wine::Exception("Wine kernel32.dll:wine_get_unix_file_name failed.");
	}
	result = tmp;
	HeapFree(GetProcessHeap(), 0, tmp);
	tmp = nullptr;
	return result;
}

mpt::PathString Context::PathToWindows(std::string hostPath)
{
	mpt::PathString result;
	if(hostPath.empty())
	{
		return result;
	}
	if(hostPath.length() >= 32000)
	{
		throw mpt::Wine::Exception("Path too long.");
	}
	LPWSTR tmp = nullptr;
	tmp = wine_get_dos_file_name(hostPath.c_str());
	if(!tmp)
	{
		throw mpt::Wine::Exception("Wine kernel32.dll:wine_get_dos_file_name failed.");
	}
	result = mpt::PathString::FromWide(tmp);
	HeapFree(GetProcessHeap(), 0, tmp);
	tmp = nullptr;
	return result;
}

std::string Context::PathToPosixCanonical(mpt::PathString windowsPath)
{
	std::string result;
	std::string hostPath = PathToPosix(windowsPath);
	if(hostPath.empty())
	{
		return result;
	}
	std::string output;
	std::string error;
	int exitcode = ExecutePosixShellCommand(std::string() + "readlink -f " + EscapePosixShell(hostPath), output, error);
	if(!error.empty())
	{
		throw mpt::Wine::Exception("Wine readlink failed: " + error);
	}
	if(exitcode != 0 && exitcode != 1)
	{
		throw mpt::Wine::Exception("Wine readlink failed.");
	}
	std::string trimmedOutput = mpt::String::Trim(output, std::string("\r\n"));
	result = trimmedOutput;
	return result;
}


static void ExecutePosixCommandProgressDefault(void * /*userdata*/ )
{
	::Sleep(10);
	return;
}

static ExecuteProgressResult ExecutePosixShellScriptProgressDefault(void * /*userdata*/ )
{
	::Sleep(10);
	return ExecuteProgressContinueWaiting;
}


std::string Context::EscapePosixShell(std::string line)
{
	const char escape_chars [] = { '|', '&', ';', '<', '>', '(', ')', '$', '`', '"', '\'', ' ', '\t' };
	const char maybe_escape_chars [] = { '*', '?', '[', '#', '~', '=', '%' };
	line = mpt::String::Replace(line, "\\", "\\\\");
	for(char c : escape_chars)
	{
		line = mpt::String::Replace(line, std::string(1, c), "\\" + std::string(1, c));
	}
	for(char c : maybe_escape_chars)
	{
		line = mpt::String::Replace(line, std::string(1, c), "\\" + std::string(1, c));
	}
	return line;
}


ExecResult Context::ExecutePosixShellScript(std::string script, FlagSet<ExecFlags> flags, std::map<std::string, std::vector<char> > filetree, std::string title, ExecutePosixCommandProgress progress, ExecutePosixShellScriptProgress progressCancel, void *userdata)
{
	// Relevant documentation:
	// https://stackoverflow.com/questions/6004070/execute-shell-commands-from-program-running-in-wine
	// https://www.winehq.org/pipermail/wine-bugs/2014-January/374918.html
	// https://bugs.winehq.org/show_bug.cgi?id=34730

	if(!progress) progress = &ExecutePosixCommandProgressDefault;
	if(!progressCancel) progressCancel = &ExecutePosixShellScriptProgressDefault;

	if(flags[ExecFlagInteractive]) flags.reset(ExecFlagSilent);
	if(flags[ExecFlagSplitOutput]) flags.set(ExecFlagSilent);

	std::vector<mpt::PathString> tempfiles;

	progress(userdata);

	mpt::TempDirGuard dirWindowsTemp(mpt::CreateTempFileName());
	if(dirWindowsTemp.GetDirname().empty())
	{
		throw mpt::Wine::Exception("Creating temporary directoy failed.");
	}
	std::string dirPosix = PathToPosix(dirWindowsTemp.GetDirname());
	if(dirPosix.empty())
	{
		throw mpt::Wine::Exception("mpt::Wine::ConvertWindowsPathToHost returned empty path.");
	}
	const mpt::PathString dirWindows = dirWindowsTemp.GetDirname();

	progress(userdata);

	// write the script to disk
	mpt::PathString scriptFilenameWindows = dirWindows + P_("script.sh");
	{
		mpt::ofstream tempfile(scriptFilenameWindows, std::ios::binary);
		tempfile << script;
		tempfile.flush();
		if(!tempfile)
		{
			throw mpt::Wine::Exception("Error writing script.sh.");
		}
	}
	std::string scriptFilenamePosix = PathToPosix(scriptFilenameWindows);
	if(scriptFilenamePosix.empty())
	{
		throw mpt::Wine::Exception("Error converting script.sh path.");
	}

	progress(userdata);

	// create a wrapper that will call the script and gather result.
	mpt::PathString wrapperstarterFilenameWindows = dirWindows + P_("wrapperstarter.sh");
	{
		mpt::ofstream tempfile(wrapperstarterFilenameWindows, std::ios::binary);
		std::string wrapperstarterscript;
		wrapperstarterscript += std::string() + "#!/usr/bin/env sh" + "\n";
		wrapperstarterscript += std::string() + "exec /usr/bin/env sh " + EscapePosixShell(dirPosix) + "wrapper.sh" + "\n";
		tempfile << wrapperstarterscript;
		tempfile.flush();
		if(!tempfile)
		{
			throw mpt::Wine::Exception("Error writing wrapper.sh.");
		}
	}
	mpt::PathString wrapperFilenameWindows = dirWindows + P_("wrapper.sh");
	std::string cleanupscript;
	{
		mpt::ofstream tempfile(wrapperFilenameWindows, std::ios::binary);
		std::string wrapperscript;
		if(!flags[ExecFlagSilent])
		{
			wrapperscript += std::string() + "printf \"\\033]0;" + title + "\\a\"" + "\n";
		}
		wrapperscript += std::string() + "chmod u+x " + EscapePosixShell(scriptFilenamePosix) + "\n";
		wrapperscript += std::string() + "cd " + EscapePosixShell(dirPosix) + "filetree" + "\n";
		if(flags[ExecFlagInteractive])
		{ // no stdout/stderr capturing for interactive scripts
			wrapperscript += std::string() + EscapePosixShell(scriptFilenamePosix) + "\n";
			wrapperscript += std::string() + "MPT_RESULT=$?" + "\n";
			wrapperscript += std::string() + "echo ${MPT_RESULT} > " + EscapePosixShell(dirPosix) + "exit" + "\n";
		} else if(flags[ExecFlagSplitOutput])
		{
			wrapperscript += std::string() + "(" + EscapePosixShell(scriptFilenamePosix) + "; echo $? >&4) 4>" + EscapePosixShell(dirPosix) + "exit 1>" + EscapePosixShell(dirPosix) + "out 2>" + EscapePosixShell(dirPosix) + "err" + "\n";
		} else
		{
			wrapperscript += std::string() + "(" + EscapePosixShell(scriptFilenamePosix) + "; echo $? >&4) 2>&1 4>" + EscapePosixShell(dirPosix) + "exit | tee " + EscapePosixShell(dirPosix) + "out" + "\n";
		}
		wrapperscript += std::string() + "echo done > " + EscapePosixShell(dirPosix) + "done" + "\n";
		cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "done" + "\n";
		cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "exit" + "\n";
		if(flags[ExecFlagInteractive])
		{
			// nothing
		} else if(flags[ExecFlagSplitOutput])
		{
			cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "out" + "\n";
			cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "err" + "\n";
		} else
		{
			cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "out" + "\n";
		}
		cleanupscript += std::string() + "rm -r " + EscapePosixShell(dirPosix) + "filetree" + "\n";
		cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "script.sh" + "\n";
		cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "wrapper.sh" + "\n";
		cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "wrapperstarter.sh" + "\n";
		cleanupscript += std::string() + "rm " + EscapePosixShell(dirPosix) + "terminal.sh" + "\n";
		if(flags[ExecFlagAsync])
		{
			wrapperscript += cleanupscript;
			cleanupscript.clear();
		}
		tempfile << wrapperscript;
		tempfile.flush();
		if(!tempfile)
		{
			throw mpt::Wine::Exception("Error writing wrapper.sh.");
		}
	}

	progress(userdata);

	::CreateDirectory((dirWindows + P_("filetree")).AsNative().c_str(), NULL);
	for(const auto &file : filetree)
	{
		std::vector<mpt::ustring> path = mpt::String::Split<mpt::ustring>(mpt::ToUnicode(mpt::CharsetUTF8, file.first), U_("/"));
		mpt::PathString combinedPath = dirWindows + P_("filetree") + P_("\\");
		if(path.size() > 1)
		{
			for(std::size_t singlepath = 0; singlepath < path.size() - 1; ++singlepath)
			{
				if(path[singlepath].empty())
				{
					continue;
				}
				combinedPath += mpt::PathString::FromUnicode(path[singlepath]);
				if(!combinedPath.IsDirectory())
				{
					if(::CreateDirectory(combinedPath.AsNative().c_str(), NULL) == 0)
					{
						throw mpt::Wine::Exception("Error writing filetree.");
					}
				}
				combinedPath += P_("\\");
			}
		}
		try
		{
			mpt::LazyFileRef out(dirWindows + P_("filetree") + P_("\\") + mpt::PathString::FromUTF8(mpt::String::Replace(file.first, "/", "\\")));
			out = file.second;
		} catch(std::exception &)
		{
			throw mpt::Wine::Exception("Error writing filetree.");
		}
	}

	progress(userdata);

	// create a wrapper that will find a suitable terminal and run the wrapper script in the terminal window.
	mpt::PathString terminalWrapperFilenameWindows = dirWindows + P_("terminal.sh");
	{
		mpt::ofstream tempfile(terminalWrapperFilenameWindows, std::ios::binary);
		// NOTE:
		// Modern terminals detach themselves from the invoking shell if another instance is already present.
		// This means we cannot rely on terminal invocation being syncronous.
		static constexpr const char * terminals[] =
		{
			"x-terminal-emulator",
			"konsole",
			"mate-terminal",
			"xfce4-terminal",
			"gnome-terminal",
			"uxterm",
			"xterm",
			"rxvt",
		};
		std::string terminalscript = "\n";
		for(const std::string terminal : terminals)
		{
			// mate-terminal on Debian 8 cannot execute commands with arguments,
			// thus we use a separate script that requires no arguments to execute.
			terminalscript += "if command -v " + terminal + " 2>/dev/null 1>/dev/null ; then" "\n";
			terminalscript += " chmod u+x " + EscapePosixShell(dirPosix) + "wrapperstarter.sh" "\n";
			terminalscript += " exec `command -v " + terminal + "` -e \"" + EscapePosixShell(dirPosix) + "wrapperstarter.sh\"" "\n";
			terminalscript += "fi" "\n";
		}

		tempfile << terminalscript;
		tempfile.flush();
		if(!tempfile)
		{
			return ExecResult::Error();
		}
	}

	progress(userdata);

	// build unix command line
	std::string unixcommand;
	bool createProcessSuccess = false;

	if(!createProcessSuccess)
	{

		if(flags[ExecFlagSilent])
		{
			unixcommand = "/usr/bin/env sh \"" + EscapePosixShell(dirPosix) + "wrapper.sh\"";
		} else
		{
			unixcommand = "/usr/bin/env sh \"" + EscapePosixShell(dirPosix) + "terminal.sh\"";
		}

		progress(userdata);

		std::wstring unixcommandW = mpt::ToWide(mpt::CharsetUTF8, unixcommand);
		std::vector<WCHAR> commandline = std::vector<WCHAR>(unixcommandW.data(), unixcommandW.data() + unixcommandW.length() + 1);
		std::wstring titleW = mpt::ToWide(mpt::CharsetUTF8, title);
		std::vector<WCHAR> titleWv = std::vector<WCHAR>(titleW.data(), titleW.data() + titleW.length() + 1);
		STARTUPINFOW startupInfo;
		MemsetZero(startupInfo);
		startupInfo.lpTitle = &titleWv[0];
		startupInfo.cb = sizeof(startupInfo);
		PROCESS_INFORMATION processInformation;
		MemsetZero(processInformation);

		progress(userdata);

		BOOL success = FALSE;
		if(flags[ExecFlagSilent])
		{
			success = CreateProcessW(NULL, &commandline[0], NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &startupInfo, &processInformation);
		} else
		{
			success = CreateProcessW(NULL, &commandline[0], NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInformation);
		}

		progress(userdata);

		createProcessSuccess = (success ? true : false);

		progress(userdata);

		if(success)
		{

			if(!flags[ExecFlagAsync])
			{
				// note: execution is not syncronous with all Wine versions,
				// we additionally explicitly wait for "done" later
				while(WaitForSingleObject(processInformation.hProcess, 0) == WAIT_TIMEOUT)
				{ // wait
					if(progressCancel(userdata) != ExecuteProgressContinueWaiting)
					{
						CloseHandle(processInformation.hThread);
						CloseHandle(processInformation.hProcess);
						throw mpt::Wine::Exception("Canceled.");
					}
				}
			}

			progress(userdata);

			CloseHandle(processInformation.hThread);
			CloseHandle(processInformation.hProcess);

		}

	}

	progress(userdata);

	// Work around Wine being able to execute PIE binaries on Debian 9.
	// Luckily, /bin/bash is still non-PIE on Debian 9.

	if(!createProcessSuccess)
	{

		if(flags[ExecFlagSilent])
		{
			unixcommand = "/bin/bash \"" + EscapePosixShell(dirPosix) + "wrapper.sh\"";
		} else
		{
			unixcommand = "/bin/bash \"" + EscapePosixShell(dirPosix) + "terminal.sh\"";
		}

		progress(userdata);

		std::wstring unixcommandW = mpt::ToWide(mpt::CharsetUTF8, unixcommand);
		std::vector<WCHAR> commandline = std::vector<WCHAR>(unixcommandW.data(), unixcommandW.data() + unixcommandW.length() + 1);
		std::wstring titleW = mpt::ToWide(mpt::CharsetUTF8, title);
		std::vector<WCHAR> titleWv = std::vector<WCHAR>(titleW.data(), titleW.data() + titleW.length() + 1);
		STARTUPINFOW startupInfo;
		MemsetZero(startupInfo);
		startupInfo.lpTitle = &titleWv[0];
		startupInfo.cb = sizeof(startupInfo);
		PROCESS_INFORMATION processInformation;
		MemsetZero(processInformation);

		progress(userdata);

		BOOL success = FALSE;
		if(flags[ExecFlagSilent])
		{
			success = CreateProcessW(NULL, &commandline[0], NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &startupInfo, &processInformation);
		} else
		{
			success = CreateProcessW(NULL, &commandline[0], NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInformation);
		}

		progress(userdata);

		createProcessSuccess = (success ? true : false);

		progress(userdata);

		if(success)
		{

			if(!flags[ExecFlagAsync])
			{
				// note: execution is not syncronous with all Wine versions,
				// we additionally explicitly wait for "done" later
				while(WaitForSingleObject(processInformation.hProcess, 0) == WAIT_TIMEOUT)
				{ // wait
					if(progressCancel(userdata) != ExecuteProgressContinueWaiting)
					{
						CloseHandle(processInformation.hThread);
						CloseHandle(processInformation.hProcess);
						throw mpt::Wine::Exception("Canceled.");
					}
				}
			}

			progress(userdata);

			CloseHandle(processInformation.hThread);
			CloseHandle(processInformation.hProcess);

		}

	}

	progress(userdata);

	if(!createProcessSuccess)
	{
		throw mpt::Wine::Exception("CreateProcess failed.");
	}

	progress(userdata);

	if(flags[ExecFlagAsync])
	{
		ExecResult result;
		result.exitcode = 0;
		return result;
	}

	while(!(dirWindows + P_("done")).IsFile())
	{ // wait
		if(progressCancel(userdata) != ExecuteProgressContinueWaiting)
		{
			throw mpt::Wine::Exception("Canceled.");
		}
	}

	progress(userdata);

	int exitCode = 0;
	{
		mpt::ifstream exitFile(dirWindows + P_("exit"), std::ios::binary);
		if(!exitFile)
		{
			throw mpt::Wine::Exception("Script .exit file not found.");
		}
		std::string exitString;
		exitFile >> exitString;
		if(exitString.empty())
		{
			throw mpt::Wine::Exception("Script .exit file empty.");
		}
		exitCode = ConvertStrTo<int>(exitString);
	}

	progress(userdata);

	std::string outputString;
	if(!flags[ExecFlagInteractive])
	{
		mpt::ifstream outputFile(dirWindows + P_("out"), std::ios::binary);
		if(outputFile)
		{
			outputFile.seekg(0, std::ios::end);
			std::streampos outputFileSize = outputFile.tellg();
			outputFile.seekg(0, std::ios::beg);
			std::vector<char> outputFileBuf(mpt::saturate_cast<std::size_t>(static_cast<std::streamoff>(outputFileSize)));
			outputFile.read(&outputFileBuf[0], outputFileBuf.size());
			outputString = std::string(outputFileBuf.begin(), outputFileBuf.end());
		}
	}

	progress(userdata);

	std::string errorString;
	if(flags[ExecFlagSplitOutput])
	{
		mpt::ifstream errorFile(dirWindows + P_("err"), std::ios::binary);
		if(errorFile)
		{
			errorFile.seekg(0, std::ios::end);
			std::streampos errorFileSize = errorFile.tellg();
			errorFile.seekg(0, std::ios::beg);
			std::vector<char> errorFileBuf(mpt::saturate_cast<std::size_t>(static_cast<std::streamoff>(errorFileSize)));
			errorFile.read(&errorFileBuf[0], errorFileBuf.size());
			errorString = std::string(errorFileBuf.begin(), errorFileBuf.end());
		}
	}

	progress(userdata);

	ExecResult result;
	result.exitcode = exitCode;
	result.output = outputString;
	result.error = errorString;

	std::deque<mpt::PathString> paths;
	paths.push_back(dirWindows + P_("filetree"));
	mpt::PathString basePath = (dirWindows + P_("filetree")).EnsureTrailingSlash();
	while(!paths.empty())
	{
		mpt::PathString path = paths.front();
		paths.pop_front();
		path.EnsureTrailingSlash();
		HANDLE hFind = NULL;
		WIN32_FIND_DATA wfd;
		MemsetZero(wfd);
		hFind = FindFirstFile((path + P_("*.*")).AsNative().c_str(), &wfd);
		if(hFind != NULL && hFind != INVALID_HANDLE_VALUE)
		{
			do
			{
				mpt::PathString filename = mpt::PathString::FromNative(wfd.cFileName);
				if(filename != P_(".") && filename != P_(".."))
				{
					filename = path + filename;
					filetree[filename.ToUTF8()] = std::vector<char>();
					if(filename.IsDirectory())
					{
						paths.push_back(filename);
					} else if(filename.IsFile())
					{
						try
						{
							mpt::LazyFileRef f(filename);
							std::vector<char> buf = f;
							mpt::PathString treeFilename = mpt::PathString::FromNative(filename.AsNative().substr(basePath.AsNative().length()));
							result.filetree[treeFilename.ToUTF8()] = buf;
						} catch (std::exception &)
						{
							// nothing?!
						}
					}
				}
			} while(FindNextFile(hFind, &wfd));
			FindClose(hFind);
		}
	}

	mpt::DeleteWholeDirectoryTree(dirWindows);

	return result;

}


int Context::ExecutePosixShellCommand(std::string command, std::string & output, std::string & error)
{
	std::string script;
	script += std::string() + "#!/usr/bin/env sh" + "\n";
	script += std::string() + "exec " + command + "\n";
	mpt::Wine::ExecResult execResult = ExecutePosixShellScript
		( script
		, mpt::Wine::ExecFlagSilent | mpt::Wine::ExecFlagSplitOutput, std::map<std::string, std::vector<char> >()
		, std::string()
		, nullptr
		, nullptr
		, nullptr
		);
	output = execResult.output;
	error = execResult.error;
	return execResult.exitcode;
}


std::string Context::GetPosixEnvVar(std::string var, std::string def)
{
	// We cannot use std::getenv here because Wine overrides SOME env vars,
	// in particular, HOME is unset in the Wine environment.
	// Instead, we just spawn a shell that will catch up a sane environment on
	// its own.
	std::string output;
	std::string error;
	int exitcode = ExecutePosixShellCommand(std::string() + "echo $" + var, output, error);
	if(!error.empty())
	{
		throw mpt::Wine::Exception("Wine echo $var failed: " + error);
	}
	if(exitcode != 0)
	{
		throw mpt::Wine::Exception("Wine echo $var failed.");
	}
	std::string result = mpt::String::RTrim(output, std::string("\r\n"));
	if(result.empty())
	{
		result = def;
	}
	return result;
}


} // namespace Wine
} // namespace mpt


#else // !(MODPLUG_TRACKER && MPT_OS_WINDOWS)


MPT_MSVC_WORKAROUND_LNK4221(mptWine)


#endif // MODPLUG_TRACKER && MPT_OS_WINDOWS


OPENMPT_NAMESPACE_END