File: Misc.cpp

package info (click to toggle)
spring 98.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 41,928 kB
  • ctags: 60,665
  • sloc: cpp: 356,167; ansic: 39,434; python: 12,228; java: 12,203; awk: 5,856; sh: 1,719; xml: 997; perl: 405; php: 253; objc: 194; makefile: 72; sed: 2
file content (484 lines) | stat: -rw-r--r-- 11,484 bytes parent folder | download
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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include "Misc.h"

#ifdef __linux__
#include <unistd.h>
#include <dlfcn.h> // for dladdr(), dlopen()

#elif WIN32
#include <io.h>
#include <direct.h>
#include <process.h>
#include <shlobj.h>
#include <shlwapi.h>
#ifndef SHGFP_TYPE_CURRENT
	#define SHGFP_TYPE_CURRENT 0
#endif
#include "System/Platform/Win/WinVersion.h"

#elif __APPLE__
#include <unistd.h>
#include <mach-o/dyld.h>
#include <stdlib.h>
#include <dlfcn.h> // for dladdr(), dlopen()
#include <climits> // for PATH_MAX

#elif defined __FreeBSD__
#include <unistd.h>
#include <dlfcn.h> // for dladdr(), dlopen()
#include <sys/types.h>
#include <sys/sysctl.h>

#else

#endif

#if !defined(WIN32)
#include <sys/utsname.h> // for uname()
#include <sys/types.h> // for getpw
#include <pwd.h> // for getpw

#include <fstream>
#endif

#include <cstring>
#include <cerrno>

#include "System/Util.h"
#include "System/SafeCStrings.h"
#include "System/Log/ILog.h"
#include "System/FileSystem/FileSystem.h"

#if       defined WIN32
/**
 * Returns a handle to the currently loaded module.
 * Note: requires at least Windows 2000
 * @return handle to the currently loaded module, or NULL if an error occures
 */
static HMODULE GetCurrentModule()
{
	// both solutions use the address of this function
	// both found at:
	// http://stackoverflow.com/questions/557081/how-do-i-get-the-hmodule-for-the-currently-executing-code/557774

	// Win 2000+ solution
	MEMORY_BASIC_INFORMATION mbi = {0};
	::VirtualQuery((void*)GetCurrentModule, &mbi, sizeof(mbi));
	HMODULE hModule = reinterpret_cast<HMODULE>(mbi.AllocationBase);

	// Win XP+ solution (cleaner)
	//::GetModuleHandleEx(
	//		GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
	//		(LPCTSTR)GetCurrentModule,
	//		&hModule);

	return hModule;
}
#endif // defined WIN32

/**
 * The user might want to define the user dir manually,
 * to locate spring related data in a non-default location.
 * @link http://en.wikipedia.org/wiki/Environment_variable#Synopsis
 */
static std::string GetUserDirFromEnvVar()
{
#ifdef _WIN32
	#define HOME_ENV_VAR "LOCALAPPDATA"
#else
	#define HOME_ENV_VAR "HOME"
#endif
	char* home = getenv(HOME_ENV_VAR);
#undef HOME_ENV_VAR

	return (home == NULL) ? "" : home;
}

static std::string GetUserDirFromSystemApi()
{
#ifdef _WIN32
	TCHAR strPath[MAX_PATH + 1];
	SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strPath);
	return strPath;
#else
	struct passwd* pw = getpwuid(getuid());
	return pw->pw_dir;
#endif
}


namespace Platform
{

static std::string origCWD;


std::string GetOrigCWD()
{
	return origCWD;
}


void SetOrigCWD()
{
	if (!origCWD.empty())
		return;

	char *buf;
#ifdef WIN32
	buf = _getcwd(NULL, 0);
#else
	buf = getcwd(NULL, 0);
#endif
	origCWD = buf;
	free(buf);
	FileSystemAbstraction::EnsurePathSepAtEnd(origCWD);
}


std::string GetUserDir()
{
	std::string userDir = GetUserDirFromEnvVar();

	if (userDir.empty()) {
		// In some cases, the env var is not set,
		// for example for non-human user accounts,
		// or when starting through the UI on OS X.
		// It is unset by default on windows.
		userDir = GetUserDirFromSystemApi();
	}

	return userDir;
}

#ifndef WIN32
static std::string GetRealPath(const std::string& path) {

	std::string pathReal = path;

	// using NULL here is not supported in very old systems,
	// but should be no problem for spring
	// see for older systems:
	// http://stackoverflow.com/questions/4109638/what-is-the-safe-alternative-to-realpath
	char* pathRealC = realpath(path.c_str(), NULL);
	if (pathRealC != NULL) {
		pathReal = pathRealC;
		free(pathRealC);
		pathRealC = NULL;
	}

	if (FileSystem::GetDirectory(pathReal).empty()) {
		pathReal = GetProcessExecutablePath() + pathReal;
	}

	return pathReal;
}
#endif

// Mac OS X:        _NSGetExecutablePath() (man 3 dyld)
// Linux:           readlink /proc/self/exe
// Solaris:         getexecname()
// FreeBSD:         sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
// BSD with procfs: readlink /proc/curproc/file
// Windows:         GetModuleFileName() with hModule = NULL
std::string GetProcessExecutableFile()
{
	std::string procExeFilePath = "";
	// error will only be used if procExeFilePath stays empty
	const char* error = NULL;

#ifdef __linux__
	char file[512];
	const int ret = readlink("/proc/self/exe", file, sizeof(file)-1);
	if (ret >= 0) {
		file[ret] = '\0';
		procExeFilePath = std::string(file);
	} else {
		error = "Failed to read /proc/self/exe";
	}
#elif WIN32
	// with NULL, it will return the handle
	// for the main executable of the process
	const HMODULE hModule = GetModuleHandle(NULL);

	// fetch
	TCHAR procExeFile[MAX_PATH+1];
	const int ret = ::GetModuleFileName(hModule, procExeFile, sizeof(procExeFile));

	if ((ret != 0) && (ret != sizeof(procExeFile))) {
		procExeFilePath = std::string(procExeFile);
	} else {
		error = "Unknown";
	}

#elif __APPLE__
	uint32_t pathlen = PATH_MAX;
	char path[PATH_MAX];
	int err = _NSGetExecutablePath(path, &pathlen);
	if (err == 0) {
		procExeFilePath = GetRealPath(path);
	}
#elif defined(__FreeBSD__)
	int mib[4];
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PATHNAME;
	mib[3] = -1;
	char buf[PATH_MAX];
	size_t cb = sizeof(buf);
	int err = sysctl(mib, 4, buf, &cb, NULL, 0);
	if (err == 0) {
		procExeFilePath = buf;
	}
#else
	#error implement this
#endif

	if (procExeFilePath.empty()) {
		LOG_L(L_WARNING, "Failed to get file path of the process executable, reason: %s", error);
	}

	return procExeFilePath;
}

std::string GetProcessExecutablePath()
{
	return FileSystem::GetDirectory(GetProcessExecutableFile());
}

std::string GetModuleFile(std::string moduleName)
{
	std::string moduleFilePath = "";
	// this will only be used if moduleFilePath stays empty
	const char* error = NULL;

#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__)
#ifdef __APPLE__
	#define SHARED_LIBRARY_EXTENSION "dylib"
#else
	#define SHARED_LIBRARY_EXTENSION "so"
#endif
	void* moduleAddress = NULL;

	// find an address in the module we are looking for
	if (moduleName.empty()) {
		// look for current module
		moduleAddress = (void*) GetModuleFile;
	} else {
		// look for specified module

		// add extension if it is not in the file name
		// it could also be "libXZY.so-1.2.3"
		// -> does not have to be the end, my friend
		if (moduleName.find("." SHARED_LIBRARY_EXTENSION) == std::string::npos) {
			moduleName = moduleName + "." SHARED_LIBRARY_EXTENSION;
		}

		// will not not try to load, but return the libs address
		// if it is already loaded, NULL otherwise
		moduleAddress = dlopen(moduleName.c_str(), RTLD_LAZY | RTLD_NOLOAD);

		if (moduleAddress == NULL) {
			// if not found, try with "lib" prefix
			moduleName = "lib" + moduleName;
			moduleAddress = dlopen(moduleName.c_str(), RTLD_LAZY | RTLD_NOLOAD);
		}
	}

	if (moduleAddress != NULL) {
		// fetch info about the module containing the address we just evaluated
		Dl_info moduleInfo;
		const int ret = dladdr(moduleAddress, &moduleInfo);
		if ((ret != 0) && (moduleInfo.dli_fname != NULL)) {
			moduleFilePath = moduleInfo.dli_fname;
			// required on APPLE; does not hurt elsewhere
			moduleFilePath = GetRealPath(moduleFilePath);
		} else {
			error = dlerror();
			if (error == NULL) {
				error = "Unknown";
			}
		}
	} else {
		error = "Not loaded";
	}

#elif WIN32
	HMODULE hModule = NULL;
	if (moduleName.empty()) {
		hModule = GetCurrentModule();
	} else {
		// If this fails, we get a NULL handle
		hModule = GetModuleHandle(moduleName.c_str());
	}

	if (hModule != NULL) {
		// fetch module file name
		TCHAR moduleFile[MAX_PATH+1];
		const int ret = ::GetModuleFileName(hModule, moduleFile, sizeof(moduleFile));

		if ((ret != 0) && (ret != sizeof(moduleFile))) {
			moduleFilePath = std::string(moduleFile);
		} else {
			error = + "Unknown";
		}
	} else {
		error = "Not found";
	}
#else
	#warning implement this (or use linux version)
#endif

	if (moduleFilePath.empty()) {
		if (moduleName.empty()) {
			moduleName = "<current>";
		}
		LOG_L(L_WARNING, "Failed to get file path of the module \"%s\", reason: %s", moduleName.c_str(), error);
	}

	return UnQuote(moduleFilePath);
}
std::string GetModulePath(const std::string& moduleName)
{
	return FileSystem::GetDirectory(GetModuleFile(moduleName));
}

std::string GetOS()
{
#if defined(WIN32)
	return "Microsoft Windows\n" +
		GetOSDisplayString() + "\n" +
		GetHardwareInfoString();
#else
	struct utsname info;
	if (uname(&info) == 0) {
		return std::string(info.sysname) + " "
				+ info.release + " "
				+ info.version + " "
				+ info.machine;
	} else {
#if defined(__linux__)
		return "Linux";
#elif defined(__FreeBSD__)
		return "FreeBSD";
#elif defined(__APPLE__)
		return "Mac OS X";
#else
		#warning improve this
		return "unknown OS";
#endif
	}
#endif
}

bool Is64Bit()
{
	return (sizeof(void*) == 8);
}

#ifdef WIN32
typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

LPFN_ISWOW64PROCESS fnIsWow64Process;

/** @brief checks if the current process is running in 32bit emulation mode
    @return FALSE, TRUE, -1 on error (usually no permissions) */
bool Is32BitEmulation()
{
	BOOL bIsWow64 = FALSE;

	fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(
		GetModuleHandle(TEXT("kernel32")),"IsWow64Process");

	if (NULL != fnIsWow64Process)
	{
		if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
		{
			return false;
		}
	}
	return bIsWow64;
}
#else
// simply assume other OS don't need 32bit emulation
bool Is32BitEmulation()
{
	return false;
}
#endif

bool IsRunningInGDB() {
	#ifndef _WIN32
	char buf[1024];

	std::string fname = "/proc/" + IntToString(getppid(), "%d") + "/cmdline";
	std::ifstream f(fname.c_str());

	if (!f.good())
		return false;

	f.read(buf, sizeof(buf));
	f.close();

	return (strstr(buf, "gdb") != NULL);
	#else
	return false;
	#endif
}

std::string GetShortFileName(const std::string& file) {
#ifdef WIN32
	std::vector<TCHAR> shortPathC(file.size() + 1, 0);

	// FIXME: stackoverflow.com/questions/843843/getshortpathname-unpredictable-results
	const int length = GetShortPathName(file.c_str(), &shortPathC[0], file.size() + 1);

	if (length > 0 && length <= (file.size() + 1)) {
		return (std::string(reinterpret_cast<const char*>(&shortPathC[0])));
	}
#endif

	return file;
}

std::string ExecuteProcess(const std::string& file, std::vector<std::string> args)
{
	// "The first argument, by convention, should point to
	// the filename associated with the file being executed."
	// NOTE:
	//   spaces in the first argument or quoted file paths
	//   are not supported on Windows, so translate <file>
	//   to a short path there
	args.insert(args.begin(), GetShortFileName(file));

	// "The array of pointers must be terminated by a NULL pointer."
	// --> include one extra argument string and leave it NULL
	std::vector<char*> processArgs(args.size() + 1, NULL);
	std::string execError;

	for (size_t a = 0; a < args.size(); ++a) {
		const std::string& arg = args[a];
		const size_t argSize = arg.length() + 1;

		STRCPY_T(processArgs[a] = new char[argSize], argSize, arg.c_str());
	}

#ifdef WIN32
	#define EXECVP _execvp
#else
	#define EXECVP execvp
#endif
	if (EXECVP(args[0].c_str(), &processArgs[0]) == -1) {
		LOG("[%s] error: \"%s\" %s (%d)", __FUNCTION__, args[0].c_str(), (execError = strerror(errno)).c_str(), errno);
	}
	#undef EXECVP

	for (size_t a = 0; a < args.size(); ++a) {
		delete[] processArgs[a];
	}

	return execError;
}

} // namespace Platform