58d71e4aa6db6287ddc8d57da7f660f789063ef2
[oweals/minetest.git] / src / porting.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 /*
21         Random portability stuff
22
23         See comments in porting.h
24 */
25
26 #if defined(linux)
27         #include <unistd.h>
28 #elif defined(__APPLE__)
29         #include <unistd.h>
30         #include <mach-o/dyld.h>
31 #elif defined(__FreeBSD__)
32         #include <unistd.h>
33         #include <sys/types.h>
34         #include <sys/sysctl.h>
35 #endif
36
37 #include "porting.h"
38 #include "config.h"
39 #include "debug.h"
40 #include "filesys.h"
41 #include "log.h"
42 #include "util/string.h"
43 #include <list>
44
45 #ifdef __APPLE__
46         #include "CoreFoundation/CoreFoundation.h"
47 #endif
48
49 namespace porting
50 {
51
52 /*
53         Signal handler (grabs Ctrl-C on POSIX systems)
54 */
55
56 bool g_killed = false;
57
58 bool * signal_handler_killstatus(void)
59 {
60         return &g_killed;
61 }
62
63 #if !defined(_WIN32) // POSIX
64         #include <signal.h>
65
66 void sigint_handler(int sig)
67 {
68         if(g_killed == false)
69         {
70                 dstream<<DTIME<<"INFO: sigint_handler(): "
71                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
72
73                 // Comment out for less clutter when testing scripts
74                 /*dstream<<DTIME<<"INFO: sigint_handler(): "
75                                 <<"Printing debug stacks"<<std::endl;
76                 debug_stacks_print();*/
77
78                 g_killed = true;
79         }
80         else
81         {
82                 (void)signal(SIGINT, SIG_DFL);
83         }
84 }
85
86 void signal_handler_init(void)
87 {
88         (void)signal(SIGINT, sigint_handler);
89 }
90
91 #else // _WIN32
92         #include <signal.h>
93
94         BOOL WINAPI event_handler(DWORD sig)
95         {
96                 switch(sig)
97                 {
98                 case CTRL_C_EVENT:
99                 case CTRL_CLOSE_EVENT:
100                 case CTRL_LOGOFF_EVENT:
101                 case CTRL_SHUTDOWN_EVENT:
102
103                         if(g_killed == false)
104                         {
105                                 dstream<<DTIME<<"INFO: event_handler(): "
106                                                 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
107                                 // Comment out for less clutter when testing scripts
108                                 /*dstream<<DTIME<<"INFO: event_handler(): "
109                                                 <<"Printing debug stacks"<<std::endl;
110                                 debug_stacks_print();*/
111
112                                 g_killed = true;
113                         }
114                         else
115                         {
116                                 (void)signal(SIGINT, SIG_DFL);
117                         }
118
119                         break;
120                 case CTRL_BREAK_EVENT:
121                         break;
122                 }
123
124                 return TRUE;
125         }
126
127 void signal_handler_init(void)
128 {
129         SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
130 }
131
132 #endif
133
134 /*
135         Multithreading support
136 */
137 int getNumberOfProcessors() {
138         #if defined(_SC_NPROCESSORS_ONLN)
139                 return sysconf(_SC_NPROCESSORS_ONLN);
140         #elif defined(__FreeBSD__) || defined(__APPLE__)
141                 unsigned int len, count;
142                 len = sizeof(count);
143                 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
144         #elif defined(_GNU_SOURCE)
145                 return get_nprocs();
146         #elif defined(_WIN32)
147                 SYSTEM_INFO sysinfo;
148                 GetSystemInfo(&sysinfo);
149                 return sysinfo.dwNumberOfProcessors;
150         #elif defined(PTW32_VERSION) || defined(__hpux)
151                 return pthread_num_processors_np();
152         #else
153                 return 1;
154         #endif
155 }
156
157 /*
158         Path mangler
159 */
160
161 // Default to RUN_IN_PLACE style relative paths
162 std::string path_share = "..";
163 std::string path_user = "..";
164
165 std::string getDataPath(const char *subpath)
166 {
167         return path_share + DIR_DELIM + subpath;
168 }
169
170 void pathRemoveFile(char *path, char delim)
171 {
172         // Remove filename and path delimiter
173         int i;
174         for(i = strlen(path)-1; i>=0; i--)
175         {
176                 if(path[i] == delim)
177                         break;
178         }
179         path[i] = 0;
180 }
181
182 bool detectMSVCBuildDir(char *c_path)
183 {
184         std::string path(c_path);
185         const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
186         return (removeStringEnd(path, ends) != "");
187 }
188
189 void initializePaths()
190 {
191 #if RUN_IN_PLACE
192         /*
193                 Use relative paths if RUN_IN_PLACE
194         */
195
196         infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
197
198         /*
199                 Windows
200         */
201         #if defined(_WIN32)
202
203         const DWORD buflen = 1000;
204         char buf[buflen];
205         DWORD len;
206
207         // Find path of executable and set path_share relative to it
208         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
209         assert(len < buflen);
210         pathRemoveFile(buf, '\\');
211
212         if(detectMSVCBuildDir(buf)){
213                 infostream<<"MSVC build directory detected"<<std::endl;
214                 path_share = std::string(buf) + "\\..\\..";
215                 path_user = std::string(buf) + "\\..\\..";
216         }
217         else{
218                 path_share = std::string(buf) + "\\..";
219                 path_user = std::string(buf) + "\\..";
220         }
221
222         /*
223                 Linux
224         */
225         #elif defined(linux)
226
227         char buf[BUFSIZ];
228         memset(buf, 0, BUFSIZ);
229         // Get path to executable
230         assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
231
232         pathRemoveFile(buf, '/');
233
234         path_share = std::string(buf) + "/..";
235         path_user = std::string(buf) + "/..";
236
237         /*
238                 OS X
239         */
240         #elif defined(__APPLE__)
241
242         //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
243         //TODO: Test this code
244         char buf[BUFSIZ];
245         uint32_t len = sizeof(buf);
246         assert(_NSGetExecutablePath(buf, &len) != -1);
247
248         pathRemoveFile(buf, '/');
249
250         path_share = std::string(buf) + "/..";
251         path_user = std::string(buf) + "/..";
252
253         /*
254                 FreeBSD
255         */
256         #elif defined(__FreeBSD__)
257
258         int mib[4];
259         char buf[BUFSIZ];
260         size_t len = sizeof(buf);
261
262         mib[0] = CTL_KERN;
263         mib[1] = KERN_PROC;
264         mib[2] = KERN_PROC_PATHNAME;
265         mib[3] = -1;
266         assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
267
268         pathRemoveFile(buf, '/');
269
270         path_share = std::string(buf) + "/..";
271         path_user = std::string(buf) + "/..";
272
273         #else
274
275         //TODO: Get path of executable. This assumes working directory is bin/
276         dstream<<"WARNING: Relative path not properly supported on this platform"
277                         <<std::endl;
278         path_share = std::string("..");
279         path_user = std::string("..");
280
281         #endif
282
283 #else // RUN_IN_PLACE
284
285         /*
286                 Use platform-specific paths otherwise
287         */
288
289         infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
290
291         /*
292                 Windows
293         */
294         #if defined(_WIN32)
295
296         const DWORD buflen = 1000;
297         char buf[buflen];
298         DWORD len;
299
300         // Find path of executable and set path_share relative to it
301         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
302         assert(len < buflen);
303         pathRemoveFile(buf, '\\');
304
305         // Use ".\bin\.."
306         path_share = std::string(buf) + "\\..";
307
308         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
309         len = GetEnvironmentVariable("APPDATA", buf, buflen);
310         assert(len < buflen);
311         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
312
313         /*
314                 Linux
315         */
316         #elif defined(linux)
317
318         // Get path to executable
319         std::string bindir = "";
320         {
321                 char buf[BUFSIZ];
322                 memset(buf, 0, BUFSIZ);
323                 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
324                 pathRemoveFile(buf, '/');
325                 bindir = buf;
326         }
327
328         // Find share directory from these.
329         // It is identified by containing the subdirectory "builtin".
330         std::list<std::string> trylist;
331         std::string static_sharedir = STATIC_SHAREDIR;
332         if(static_sharedir != "" && static_sharedir != ".")
333                 trylist.push_back(static_sharedir);
334         trylist.push_back(bindir + "/../share/" + PROJECT_NAME);
335         trylist.push_back(bindir + "/..");
336
337         for(std::list<std::string>::const_iterator i = trylist.begin();
338                         i != trylist.end(); i++)
339         {
340                 const std::string &trypath = *i;
341                 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + "/builtin")){
342                         dstream<<"WARNING: system-wide share not found at \""
343                                         <<trypath<<"\""<<std::endl;
344                         continue;
345                 }
346                 // Warn if was not the first alternative
347                 if(i != trylist.begin()){
348                         dstream<<"WARNING: system-wide share found at \""
349                                         <<trypath<<"\""<<std::endl;
350                 }
351                 path_share = trypath;
352                 break;
353         }
354
355         path_user = std::string(getenv("HOME")) + "/." + PROJECT_NAME;
356
357         /*
358                 OS X
359         */
360         #elif defined(__APPLE__)
361
362     // Code based on
363     // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
364     CFBundleRef main_bundle = CFBundleGetMainBundle();
365     CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
366     char path[PATH_MAX];
367     if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
368         {
369                 dstream<<"Bundle resource path: "<<path<<std::endl;
370                 //chdir(path);
371                 path_share = std::string(path) + "/share";
372         }
373         else
374     {
375         // error!
376                 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
377     }
378     CFRelease(resources_url);
379
380         path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
381
382         #elif defined(__FreeBSD__)
383
384         path_share = STATIC_SHAREDIR;
385         path_user = std::string(getenv("HOME")) + "/." + PROJECT_NAME;
386
387         #endif
388
389 #endif // RUN_IN_PLACE
390 }
391
392 } //namespace porting
393