3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 Random portability stuff
23 See comments in porting.h
28 #if defined(__APPLE__)
29 #include <mach-o/dyld.h>
30 #include "CoreFoundation/CoreFoundation.h"
31 #elif defined(__FreeBSD__)
32 #include <sys/types.h>
33 #include <sys/sysctl.h>
36 #elif defined(__LINUX)
37 #include <sys/types.h>
42 #include <sys/utsname.h>
49 #include "util/string.h"
58 Signal handler (grabs Ctrl-C on POSIX systems)
61 bool g_killed = false;
63 bool * signal_handler_killstatus(void)
68 #if !defined(_WIN32) // POSIX
71 void sigint_handler(int sig)
75 dstream<<DTIME<<"INFO: sigint_handler(): "
76 <<"Ctrl-C pressed, shutting down."<<std::endl;
78 // Comment out for less clutter when testing scripts
79 /*dstream<<DTIME<<"INFO: sigint_handler(): "
80 <<"Printing debug stacks"<<std::endl;
81 debug_stacks_print();*/
87 (void)signal(SIGINT, SIG_DFL);
91 void signal_handler_init(void)
93 (void)signal(SIGINT, sigint_handler);
99 BOOL WINAPI event_handler(DWORD sig)
104 case CTRL_CLOSE_EVENT:
105 case CTRL_LOGOFF_EVENT:
106 case CTRL_SHUTDOWN_EVENT:
108 if(g_killed == false)
110 dstream<<DTIME<<"INFO: event_handler(): "
111 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
112 // Comment out for less clutter when testing scripts
113 /*dstream<<DTIME<<"INFO: event_handler(): "
114 <<"Printing debug stacks"<<std::endl;
115 debug_stacks_print();*/
121 (void)signal(SIGINT, SIG_DFL);
125 case CTRL_BREAK_EVENT:
132 void signal_handler_init(void)
134 SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
141 Multithreading support
143 int getNumberOfProcessors()
145 #if defined(_SC_NPROCESSORS_ONLN)
147 return sysconf(_SC_NPROCESSORS_ONLN);
149 #elif defined(__FreeBSD__) || defined(__APPLE__)
151 unsigned int len, count;
153 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
155 #elif defined(_GNU_SOURCE)
159 #elif defined(_WIN32)
162 GetSystemInfo(&sysinfo);
163 return sysinfo.dwNumberOfProcessors;
165 #elif defined(PTW32_VERSION) || defined(__hpux)
167 return pthread_num_processors_np();
177 bool threadBindToProcessor(threadid_t tid, int pnumber)
181 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
185 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
187 CloseHandle(hThread);
190 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
191 || defined(__linux) || defined(linux)
196 CPU_SET(pnumber, &cpuset);
197 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
199 #elif defined(__sun) || defined(sun)
201 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
206 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
208 #elif defined(__hpux) || defined(hpux)
210 pthread_spu_t answer;
212 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
213 &answer, pnumber, tid) == 0;
215 #elif defined(__APPLE__)
217 struct thread_affinity_policy tapol;
219 thread_port_t threadport = pthread_mach_thread_np(tid);
220 tapol.affinity_tag = pnumber + 1;
221 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
222 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
232 bool threadSetPriority(threadid_t tid, int prio)
236 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
240 bool success = SetThreadPriority(hThread, prio) != 0;
242 CloseHandle(hThread);
247 struct sched_param sparam;
250 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
253 int min = sched_get_priority_min(policy);
254 int max = sched_get_priority_max(policy);
256 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
257 return pthread_setschedparam(tid, policy, &sparam) == 0;
267 // Default to RUN_IN_PLACE style relative paths
268 std::string path_share = "..";
269 std::string path_user = "..";
271 std::string getDataPath(const char *subpath)
273 return path_share + DIR_DELIM + subpath;
276 void pathRemoveFile(char *path, char delim)
278 // Remove filename and path delimiter
280 for(i = strlen(path)-1; i>=0; i--)
288 bool detectMSVCBuildDir(char *c_path)
290 std::string path(c_path);
291 const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
292 return (removeStringEnd(path, ends) != "");
295 std::string get_sysinfo()
299 std::ostringstream oss;
301 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
302 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
304 tmp = osvi.szCSDVersion;
305 std::replace(tmp.begin(), tmp.end(), ' ', '_');
307 oss << "Windows/" << osvi.dwMajorVersion << "."
308 << osvi.dwMinorVersion;
309 if(osvi.szCSDVersion[0])
316 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
317 oss << "x86_64"; // 32-bit app on 64-bit OS
324 struct utsname osinfo;
326 return std::string(osinfo.sysname) + "/"
327 + osinfo.release + " " + osinfo.machine;
331 void initializePaths()
335 Use relative paths if RUN_IN_PLACE
338 infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
345 const DWORD buflen = 1000;
349 // Find path of executable and set path_share relative to it
350 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
351 assert(len < buflen);
352 pathRemoveFile(buf, '\\');
354 if(detectMSVCBuildDir(buf)){
355 infostream<<"MSVC build directory detected"<<std::endl;
356 path_share = std::string(buf) + "\\..\\..";
357 path_user = std::string(buf) + "\\..\\..";
360 path_share = std::string(buf) + "\\..";
361 path_user = std::string(buf) + "\\..";
370 memset(buf, 0, BUFSIZ);
371 // Get path to executable
372 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
374 pathRemoveFile(buf, '/');
376 path_share = std::string(buf) + "/..";
377 path_user = std::string(buf) + "/..";
382 #elif defined(__APPLE__)
384 //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
385 //TODO: Test this code
387 uint32_t len = sizeof(buf);
388 assert(_NSGetExecutablePath(buf, &len) != -1);
390 pathRemoveFile(buf, '/');
392 path_share = std::string(buf) + "/..";
393 path_user = std::string(buf) + "/..";
398 #elif defined(__FreeBSD__)
402 size_t len = sizeof(buf);
406 mib[2] = KERN_PROC_PATHNAME;
408 assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
410 pathRemoveFile(buf, '/');
412 path_share = std::string(buf) + "/..";
413 path_user = std::string(buf) + "/..";
417 //TODO: Get path of executable. This assumes working directory is bin/
418 dstream<<"WARNING: Relative path not properly supported on this platform"
421 /* scriptapi no longer allows paths that start with "..", so assuming that
422 the current working directory is bin/, strip off the last component. */
423 char *cwd = getcwd(NULL, 0);
424 pathRemoveFile(cwd, '/');
425 path_share = std::string(cwd);
426 path_user = std::string(cwd);
430 #else // RUN_IN_PLACE
433 Use platform-specific paths otherwise
436 infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
443 const DWORD buflen = 1000;
447 // Find path of executable and set path_share relative to it
448 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
449 assert(len < buflen);
450 pathRemoveFile(buf, '\\');
453 path_share = std::string(buf) + "\\..";
455 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
456 len = GetEnvironmentVariable("APPDATA", buf, buflen);
457 assert(len < buflen);
458 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
465 // Get path to executable
466 std::string bindir = "";
469 memset(buf, 0, BUFSIZ);
470 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
471 pathRemoveFile(buf, '/');
475 // Find share directory from these.
476 // It is identified by containing the subdirectory "builtin".
477 std::list<std::string> trylist;
478 std::string static_sharedir = STATIC_SHAREDIR;
479 if(static_sharedir != "" && static_sharedir != ".")
480 trylist.push_back(static_sharedir);
482 bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
483 trylist.push_back(bindir + DIR_DELIM + "..");
485 for(std::list<std::string>::const_iterator i = trylist.begin();
486 i != trylist.end(); i++)
488 const std::string &trypath = *i;
489 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
490 dstream<<"WARNING: system-wide share not found at \""
491 <<trypath<<"\""<<std::endl;
494 // Warn if was not the first alternative
495 if(i != trylist.begin()){
496 dstream<<"WARNING: system-wide share found at \""
497 <<trypath<<"\""<<std::endl;
499 path_share = trypath;
503 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
508 #elif defined(__APPLE__)
511 // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
512 CFBundleRef main_bundle = CFBundleGetMainBundle();
513 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
515 if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
517 dstream<<"Bundle resource path: "<<path<<std::endl;
519 path_share = std::string(path) + DIR_DELIM + "share";
524 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
526 CFRelease(resources_url);
528 path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
530 #else // FreeBSD, and probably many other POSIX-like systems.
532 path_share = STATIC_SHAREDIR;
533 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
537 #endif // RUN_IN_PLACE
540 static irr::IrrlichtDevice* device;
542 void initIrrlicht(irr::IrrlichtDevice * _device)
548 v2u32 getWindowSize()
550 return device->getVideoDriver()->getScreenSize();
554 float getDisplayDensity()
556 float gui_scaling = g_settings->getFloat("gui_scaling");
557 // using Y here feels like a bug, this needs to be discussed later!
558 if (getWindowSize().Y <= 800) {
559 return (2.0/3.0) * gui_scaling;
561 if (getWindowSize().Y <= 1280) {
562 return 1.0 * gui_scaling;
565 return (4.0/3.0) * gui_scaling;
568 v2u32 getDisplaySize()
570 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
572 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
573 nulldevice -> drop();
583 errorstream << "daemonize not implemented on windows" << std::endl;
585 #else // assume posix like os
587 static std::string get_pidfile_path()
589 // make it static to make sure it won't change after first call to this fct
590 static std::string path_pidfile = "";
591 static bool initialized = false;
598 g_settings->getNoEx("pidfile", path_pidfile);
600 if (path_pidfile == "") {
602 path_pidfile = "pidfile.pid";
604 path_pidfile = "/var/run/minetest.pid";
614 std::string path_pidfile = get_pidfile_path();
616 FILE* pidfile = fopen(path_pidfile.c_str(),"r");
620 if (fscanf(pidfile, "%i", &pid) == 1) {
621 if (kill(pid, 0) == 0) {
623 "Minetestserver is already running with pid: "
628 errorstream << "Pidfile \"" << path_pidfile << "\" "
629 "already exists but content is invalid" << std::endl <<
630 "Delete it manually if you're sure minetest isn't running!"
642 pidfile = fopen(path_pidfile.c_str(),"w+");
644 fprintf(pidfile,"%i",pid);
647 errorstream << "Failed to create pidfile: \"" << path_pidfile
651 } else if (pid == 0) {
652 freopen("/dev/null","w",stdout);
653 freopen("/dev/null","w",stderr);
654 freopen("/dev/null","r",stdout);
658 errorstream << "Failed to daemonize minetest, exiting" << std::endl;
664 unlink(get_pidfile_path().c_str());
669 } //namespace porting