Doxygen
Loading...
Searching...
No Matches
portable.cpp
Go to the documentation of this file.
1#include "portable.h"
2#include "qcstring.h"
3
4#include <stdlib.h>
5#include <stdio.h>
6#include <chrono>
7#include <thread>
8#include <mutex>
9#include <map>
10
11#if defined(_WIN32) && !defined(__CYGWIN__)
12#undef UNICODE
13#define _WIN32_DCOM
14#include <windows.h>
15#else
16#include <unistd.h>
17#include <sys/types.h>
18#include <sys/wait.h>
19#include <errno.h>
20extern char **environ;
21#endif
22
23#include <assert.h>
24#include <ctype.h>
25#include <map>
26#include <string>
27
28#include "fileinfo.h"
29#include "message.h"
30
31#include "util.h"
32#include "dir.h"
33#ifndef NODEBUG
34#include "debug.h"
35#endif
36
37#if !defined(_WIN32) || defined(__CYGWIN__)
38static bool environmentLoaded = false;
39static std::map<std::string,std::string> proc_env = std::map<std::string,std::string>();
40#endif
41
42
43//---------------------------------------------------------------------------------------------------------
44
45/*! Helper class to keep time interval per thread */
47{
48 public:
49 static SysTimeKeeper &instance();
50 //! start a timer for this thread
51 void start()
52 {
53 std::lock_guard<std::mutex> lock(m_mutex);
54 m_startTimes[std::this_thread::get_id()] = std::chrono::steady_clock::now();
55 }
56 //! ends a timer for this thread, accumulate time difference since start
57 void stop()
58 {
59 std::lock_guard<std::mutex> lock(m_mutex);
60 std::chrono::steady_clock::time_point endTime = std::chrono::steady_clock::now();
61 auto it = m_startTimes.find(std::this_thread::get_id());
62 if (it == m_startTimes.end())
63 {
64 err("SysTimeKeeper stop() called without matching start()\n");
65 return;
66 }
67 double timeSpent = static_cast<double>(std::chrono::duration_cast<
68 std::chrono::microseconds>(endTime - it->second).count())/1000000.0;
69 //printf("timeSpent on thread %zu: %.4f seconds\n",std::hash<std::thread::id>{}(std::this_thread::get_id()),timeSpent);
70 m_elapsedTime += timeSpent;
71 }
72
73 double elapsedTime() const { return m_elapsedTime; }
74
75 private:
76 struct TimeData
77 {
78 std::chrono::steady_clock::time_point startTime;
79 };
80 std::map<std::thread::id,std::chrono::steady_clock::time_point> m_startTimes;
81 double m_elapsedTime = 0;
82 std::mutex m_mutex;
83};
84
86{
87 static SysTimeKeeper theInstance;
88 return theInstance;
89}
90
97
102
103//---------------------------------------------------------------------------------------------------------
104
105
106int Portable::system(const QCString &command,const QCString &args,bool commandHasConsole)
107{
108 if (command.isEmpty()) return 1;
109 AutoTimeKeeper timeKeeper;
110
111#if defined(_WIN32) && !defined(__CYGWIN__)
112 QCString commandCorrectedPath = substitute(command,'/','\\');
113 QCString fullCmd=commandCorrectedPath;
114#else
115 QCString fullCmd=command;
116#endif
117 fullCmd=fullCmd.stripWhiteSpace();
118 if (fullCmd.at(0)!='"' && fullCmd.find(' ')!=-1)
119 {
120 // add quotes around command as it contains spaces and is not quoted already
121 fullCmd="\""+fullCmd+"\"";
122 }
123 fullCmd += " ";
124 fullCmd += args;
125#ifndef NODEBUG
126 Debug::print(Debug::ExtCmd,0,"Executing external command `{}`\n",fullCmd);
127#endif
128
129#if !defined(_WIN32) || defined(__CYGWIN__)
130 (void)commandHasConsole;
131 /*! taken from the system() manpage on my Linux box */
132 int pid,status=0;
133
134#ifdef _OS_SOLARIS // for Solaris we use vfork since it is more memory efficient
135
136 // on Solaris fork() duplicates the memory usage
137 // so we use vfork instead
138
139 // spawn shell
140 if ((pid=vfork())<0)
141 {
142 status=-1;
143 }
144 else if (pid==0)
145 {
146 execl("/bin/sh","sh","-c",fullCmd.data(),(char*)0);
147 _exit(127);
148 }
149 else
150 {
151 while (waitpid(pid,&status,0 )<0)
152 {
153 if (errno!=EINTR)
154 {
155 status=-1;
156 break;
157 }
158 }
159 }
160 return status;
161
162#else // Other Unices just use fork
163
164 pid = fork();
165 if (pid==-1)
166 {
167 perror("fork error");
168 return -1;
169 }
170 if (pid==0)
171 {
172 const char * const argv[4] = { "sh", "-c", fullCmd.data(), 0 };
173 execve("/bin/sh",const_cast<char * const*>(argv),environ);
174 exit(127);
175 }
176 for (;;)
177 {
178 if (waitpid(pid,&status,0)==-1)
179 {
180 if (errno!=EINTR) return -1;
181 }
182 else
183 {
184 if (WIFEXITED(status))
185 {
186 return WEXITSTATUS(status);
187 }
188 else
189 {
190 return status;
191 }
192 }
193 }
194#endif // !_OS_SOLARIS
195
196#else // Win32 specific
197 if (commandHasConsole)
198 {
199 return ::system(fullCmd.data());
200 }
201 else
202 {
203 uint16_t* fullCmdW = nullptr;
204 recodeUtf8StringToW(fullCmd, &fullCmdW);
205
206 STARTUPINFOW sStartupInfo;
207 std::memset(&sStartupInfo, 0, sizeof(sStartupInfo));
208 sStartupInfo.cb = sizeof(sStartupInfo);
209 sStartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
210 sStartupInfo.wShowWindow = SW_HIDE;
211
212 PROCESS_INFORMATION sProcessInfo;
213 std::memset(&sProcessInfo, 0, sizeof(sProcessInfo));
214
215 if (!CreateProcessW(
216 nullptr, // No module name (use command line)
217 reinterpret_cast<wchar_t*>(fullCmdW), // Command line, can be mutated by CreateProcessW
218 nullptr, // Process handle not inheritable
219 nullptr, // Thread handle not inheritable
220 FALSE, // Set handle inheritance to FALSE
221 CREATE_NO_WINDOW,
222 nullptr, // Use parent's environment block
223 nullptr, // Use parent's starting directory
224 &sStartupInfo,
225 &sProcessInfo
226 ))
227 {
228 delete[] fullCmdW;
229 return -1;
230 }
231 else if (sProcessInfo.hProcess) /* executable was launched, wait for it to finish */
232 {
233 WaitForSingleObject(sProcessInfo.hProcess,INFINITE);
234 /* get process exit code */
235 DWORD exitCode;
236 bool retval = GetExitCodeProcess(sProcessInfo.hProcess,&exitCode);
237 CloseHandle(sProcessInfo.hProcess);
238 CloseHandle(sProcessInfo.hThread);
239 delete[] fullCmdW;
240 if (!retval) return -1;
241 return exitCode;
242 }
243 }
244#endif
245 return 1; // we should never get here
246
247}
248
250{
251 uint32_t pid;
252#if !defined(_WIN32) || defined(__CYGWIN__)
253 pid = static_cast<uint32_t>(getpid());
254#else
255 pid = static_cast<uint32_t>(GetCurrentProcessId());
256#endif
257 return pid;
258}
259
260#if !defined(_WIN32) || defined(__CYGWIN__)
262{
263 if(environ != nullptr)
264 {
265 unsigned int i = 0;
266 char* current = environ[i];
267
268 while(current != nullptr) // parse all strings contained by environ til the last element (nullptr)
269 {
270 std::string env_var(current); // load current environment variable string
271 size_t pos = env_var.find("=");
272 if(pos != std::string::npos) // only parse the variable, if it is a valid environment variable...
273 { // ...which has to contain an equal sign as delimiter by definition
274 std::string name = env_var.substr(0,pos); // the string til the equal sign contains the name
275 std::string value = env_var.substr(pos + 1); // the string from the equal sign contains the value
276 proc_env[name] = std::move(value); // save the value by the name as its key in the classes map
277 }
278 i++;
279 current = environ[i];
280 }
281 }
282
283 environmentLoaded = true;
284}
285#endif
286
287void Portable::setenv(const QCString &name,const QCString &value)
288{
289#if defined(_WIN32) && !defined(__CYGWIN__)
290 SetEnvironmentVariable(name.data(),!value.isEmpty() ? value.data() : "");
291#else
292 if(!environmentLoaded) // if the environment variables are not loaded already...
293 { // ...call loadEnvironment to store them in class
295 }
296
297 proc_env[name.str()] = value.str(); // create or replace existing value
298 ::setenv(name.data(),value.data(),1);
299#endif
300}
301
302void Portable::unsetenv(const QCString &variable)
303{
304#if defined(_WIN32) && !defined(__CYGWIN__)
305 SetEnvironmentVariable(variable.data(),nullptr);
306#else
307 /* Some systems don't have unsetenv(), so we do it ourselves */
308 if (variable.isEmpty() || variable.find('=')!=-1)
309 {
310 return; // not properly formatted
311 }
312
313 auto it = proc_env.find(variable.str());
314 if (it != proc_env.end())
315 {
316 proc_env.erase(it);
317 ::unsetenv(variable.data());
318 }
319#endif
320}
321
323{
324#if defined(_WIN32) && !defined(__CYGWIN__)
325 #define ENV_BUFSIZE 32768
326 LPTSTR pszVal = (LPTSTR) malloc(ENV_BUFSIZE*sizeof(TCHAR));
327 if (GetEnvironmentVariable(variable.data(),pszVal,ENV_BUFSIZE) == 0) return "";
328 QCString out;
329 out = pszVal;
330 free(pszVal);
331 return out;
332 #undef ENV_BUFSIZE
333#else
334 if(!environmentLoaded) // if the environment variables are not loaded already...
335 { // ...call loadEnvironment to store them in class
337 }
338
339 if (proc_env.find(variable.str()) != proc_env.end())
340 {
341 return QCString(proc_env[variable.str()]);
342 }
343 else
344 {
345 return QCString();
346 }
347#endif
348}
349
350FILE *Portable::fopen(const QCString &fileName,const QCString &mode)
351{
352#if defined(_WIN32) && !defined(__CYGWIN__)
353 uint16_t *fn = nullptr;
354 size_t fn_len = recodeUtf8StringToW(fileName,&fn);
355 uint16_t *m = nullptr;
356 size_t m_len = recodeUtf8StringToW(mode,&m);
357 FILE *result = nullptr;
358 if (fn_len!=(size_t)-1 && m_len!=(size_t)-1)
359 {
360 result = _wfopen((wchar_t*)fn,(wchar_t*)m);
361 }
362 delete[] fn;
363 delete[] m;
364 return result;
365#else
366 return ::fopen(fileName.data(),mode.data());
367#endif
368}
369
371{
372 return ::fclose(f);
373}
374
376{
377#if defined(_WIN32) && !defined(__CYGWIN__)
378 return "\\";
379#else
380 return "/";
381#endif
382}
383
385{
386#if defined(_WIN32) && !defined(__CYGWIN__)
387 return ";";
388#else
389 return ":";
390#endif
391}
392
393static bool ExistsOnPath(const QCString &fileName)
394{
395 FileInfo fi1(fileName.str());
396 if (fi1.exists()) return true;
397
398 QCString paths = Portable::getenv("PATH");
399 char listSep = Portable::pathListSeparator()[0];
400 char pathSep = Portable::pathSeparator()[0];
401 int strt = 0;
402 int idx;
403 while ((idx = paths.find(listSep,strt)) != -1)
404 {
405 QCString locFile(paths.mid(strt,idx-strt));
406 locFile += pathSep;
407 locFile += fileName;
408 FileInfo fi(locFile.str());
409 if (fi.exists()) return true;
410 strt = idx + 1;
411 }
412 // to be sure the last path component is checked as well
413 QCString locFile(paths.mid(strt));
414 if (!locFile.isEmpty())
415 {
416 locFile += pathSep;
417 locFile += fileName;
418 FileInfo fi(locFile.str());
419 if (fi.exists()) return true;
420 }
421 return false;
422}
423
425{
426#if defined(_WIN32) && !defined(__CYGWIN__)
427 const char *extensions[] = {".bat",".com",".exe"};
428 for (int i = 0; i < sizeof(extensions) / sizeof(*extensions); i++)
429 {
430 if (ExistsOnPath(fileName + extensions[i])) return true;
431 }
432 return false;
433#else
434 return ExistsOnPath(fileName);
435#endif
436}
437
439{
440#if defined(_WIN32) && !defined(__CYGWIN__)
441 static const char *gsexe = nullptr;
442 if (!gsexe)
443 {
444 const char *gsExec[] = {"gswin32c.exe","gswin64c.exe"};
445 for (int i = 0; i < sizeof(gsExec) / sizeof(*gsExec); i++)
446 {
447 if (ExistsOnPath(gsExec[i]))
448 {
449 gsexe = gsExec[i];
450 return gsexe;
451 }
452 }
453 gsexe = gsExec[0];
454 return gsexe;
455 }
456 return gsexe;
457#else
458 return "gs";
459#endif
460}
461
463{
464#if defined(_WIN32) && !defined(__CYGWIN__)
465 return ".exe";
466#else
467 return "";
468#endif
469}
470
472{
473#if defined(_WIN32) || defined(macintosh) || defined(__MACOSX__) || defined(__APPLE__) || defined(__CYGWIN__)
474 return FALSE;
475#else
476 return TRUE;
477#endif
478}
479
480FILE * Portable::popen(const QCString &name,const QCString &type)
481{
482 #if defined(_MSC_VER) || defined(__BORLANDC__)
483 return ::_popen(name.data(),type.data());
484 #else
485 return ::popen(name.data(),type.data());
486 #endif
487}
488
489int Portable::pclose(FILE *stream)
490{
491 #if defined(_MSC_VER) || defined(__BORLANDC__)
492 return ::_pclose(stream);
493 #else
494 return ::pclose(stream);
495 #endif
496}
497
499{
500 const char *fn = fileName.data();
501# ifdef _WIN32
502 if (fileName.length()>1 && isalpha(fileName[0]) && fileName[1]==':') fn+=2;
503# endif
504 char const fst = fn[0];
505 if (fst == '/') return true;
506# ifdef _WIN32
507 if (fst == '\\') return true;
508# endif
509 return false;
510}
511
512/**
513 * Correct a possible wrong PATH variable
514 *
515 * This routine was inspired by the cause for bug 766059 was that in the Windows path there were forward slashes.
516 */
517void Portable::correctPath(const StringVector &extraPaths)
518{
519 QCString p = Portable::getenv("PATH");
520 bool first=true;
521 QCString result;
522#if defined(_WIN32) && !defined(__CYGWIN__)
523 for (const auto &path : extraPaths)
524 {
525 if (!first) result+=';';
526 first=false;
527 result += substitute(QCString(path),"/","\\");
528 }
529 if (!result.isEmpty() && !p.isEmpty()) result+=';';
530 result += substitute(p,"/","\\");
531#else
532 for (const auto &path : extraPaths)
533 {
534 if (!first) result+=':';
535 first=false;
536 result += QCString(path);
537 }
538 if (!result.isEmpty() && !p.isEmpty()) result+=':';
539 result += p;
540#endif
541 if (result!=p) Portable::setenv("PATH",result.data());
542 //printf("settingPath(%s) #extraPaths=%zu\n",Portable::getenv("PATH").data(),extraPaths.size());
543}
544
545void Portable::unlink(const QCString &fileName)
546{
547#if defined(_WIN32) && !defined(__CYGWIN__)
548 _unlink(fileName.data());
549#else
550 ::unlink(fileName.data());
551#endif
552}
553
555{
556#if defined(_WIN32) && !defined(__CYGWIN__)
557 long length = 0;
558 TCHAR* buffer = nullptr;
559 // First obtain the size needed by passing nullptr and 0.
560 length = GetShortPathName(Dir::currentDirPath().c_str(), nullptr, 0);
561 // Dynamically allocate the correct size
562 // (terminating null char was included in length)
563 buffer = new TCHAR[length];
564 // Now simply call again using same (long) path.
565 length = GetShortPathName(Dir::currentDirPath().c_str(), buffer, length);
566 // Set the correct directory (short name)
567 Dir::setCurrent(buffer);
568 delete [] buffer;
569#endif
570}
571
572/* Return the first occurrence of NEEDLE in HAYSTACK. */
573static const char * portable_memmem (const char *haystack, size_t haystack_len,
574 const char *needle, size_t needle_len)
575{
576 const char *const last_possible = haystack + haystack_len - needle_len;
577
578 if (needle_len == 0)
579 // The first occurrence of the empty string should to occur at the beginning of the string.
580 {
581 return haystack;
582 }
583
584 // Sanity check
585 if (haystack_len < needle_len)
586 {
587 return nullptr;
588 }
589
590 for (const char *begin = haystack; begin <= last_possible; ++begin)
591 {
592 if (begin[0] == needle[0] && !memcmp(&begin[1], needle + 1, needle_len - 1))
593 {
594 return begin;
595 }
596 }
597
598 return nullptr;
599}
600
601const char *Portable::strnstr(const char *haystack, const char *needle, size_t haystack_len)
602{
603 size_t needle_len = strnlen(needle, haystack_len);
604 if (needle_len < haystack_len || !needle[needle_len])
605 {
606 const char *x = portable_memmem(haystack, haystack_len, needle, needle_len);
607 if (x && !memchr(haystack, 0, x - haystack))
608 {
609 return x;
610 }
611 }
612 return nullptr;
613}
614
615const char *Portable::devNull()
616{
617#if defined(_WIN32) && !defined(__CYGWIN__)
618 return "NUL";
619#else
620 return "/dev/null";
621#endif
622}
623
624size_t Portable::recodeUtf8StringToW(const QCString &inputStr,uint16_t **outBuf)
625{
626 if (inputStr.isEmpty() || outBuf==nullptr) return 0; // empty input or invalid output
627 void *handle = portable_iconv_open("UTF-16LE","UTF-8");
628 if (handle==reinterpret_cast<void *>(-1)) return 0; // invalid encoding
629 size_t len = inputStr.length();
630 uint16_t *buf = new uint16_t[len+1];
631 *outBuf = buf;
632 size_t inRemains = len;
633 size_t outRemains = len*sizeof(uint16_t)+2; // chars + \0
634 const char *p = inputStr.data();
635 portable_iconv(handle,&p,&inRemains,reinterpret_cast<char **>(&buf),&outRemains);
636 *buf=0;
637 portable_iconv_close(handle);
638 return len;
639}
640
641//----------------------------------------------------------------------------------------
642// We need to do this part last as including filesystem.hpp earlier
643// causes the code above to fail to compile on Windows.
644
645#include "filesystem.hpp"
646
647namespace fs = ghc::filesystem;
648
649std::ofstream Portable::openOutputStream(const QCString &fileName,bool append)
650{
651 std::ios_base::openmode mode = std::ofstream::out | std::ofstream::binary;
652 if (append) mode |= std::ofstream::app;
653#if defined(__clang__) && defined(__MINGW32__)
654 return std::ofstream(fs::path(fileName.str()).wstring(), mode);
655#else
656 return std::ofstream(fs::path(fileName.str()), mode);
657#endif
658}
659
660std::ifstream Portable::openInputStream(const QCString &fileName,bool binary, bool openAtEnd)
661{
662 std::ios_base::openmode mode = std::ifstream::in | std::ifstream::binary;
663 if (binary) mode |= std::ios::binary;
664 if (openAtEnd) mode |= std::ios::ate;
665#if defined(__clang__) && defined(__MINGW32__)
666 return std::ifstream(fs::path(fileName.str()).wstring(), mode);
667#else
668 return std::ifstream(fs::path(fileName.str()), mode);
669#endif
670}
671
@ ExtCmd
Definition debug.h:36
static void print(DebugMask mask, int prio, fmt::format_string< Args... > fmt, Args &&... args)
Definition debug.h:76
static std::string currentDirPath()
Definition dir.cpp:342
static bool setCurrent(const std::string &path)
Definition dir.cpp:350
Minimal replacement for QFileInfo.
Definition fileinfo.h:23
bool exists() const
Definition fileinfo.cpp:30
This is an alternative implementation of QCString.
Definition qcstring.h:101
int find(char c, int index=0, bool cs=TRUE) const
Definition qcstring.cpp:43
size_t length() const
Returns the length of the string, not counting the 0-terminator.
Definition qcstring.h:153
QCString mid(size_t index, size_t len=static_cast< size_t >(-1)) const
Definition qcstring.h:226
char & at(size_t i)
Returns a reference to the character at index i.
Definition qcstring.h:578
bool isEmpty() const
Returns TRUE iff the string is empty.
Definition qcstring.h:150
QCString stripWhiteSpace() const
returns a copy of this string with leading and trailing whitespace removed
Definition qcstring.h:245
const std::string & str() const
Definition qcstring.h:537
const char * data() const
Returns a pointer to the contents of the string in the form of a 0-terminated C string.
Definition qcstring.h:159
std::mutex m_mutex
Definition portable.cpp:82
double m_elapsedTime
Definition portable.cpp:81
void stop()
ends a timer for this thread, accumulate time difference since start
Definition portable.cpp:57
void start()
start a timer for this thread
Definition portable.cpp:51
double elapsedTime() const
Definition portable.cpp:73
static SysTimeKeeper & instance()
Definition portable.cpp:85
std::map< std::thread::id, std::chrono::steady_clock::time_point > m_startTimes
Definition portable.cpp:80
std::vector< std::string > StringVector
Definition containers.h:33
DirIterator begin(DirIterator it) noexcept
Definition dir.cpp:170
#define err(fmt,...)
Definition message.h:127
std::ifstream openInputStream(const QCString &name, bool binary=false, bool openAtEnd=false)
Definition portable.cpp:660
void correctPath(const StringVector &list)
Correct a possible wrong PATH variable.
Definition portable.cpp:517
bool isAbsolutePath(const QCString &fileName)
Definition portable.cpp:498
QCString pathSeparator()
Definition portable.cpp:375
FILE * popen(const QCString &name, const QCString &type)
Definition portable.cpp:480
std::ofstream openOutputStream(const QCString &name, bool append=false)
Definition portable.cpp:649
double getSysElapsedTime()
Definition portable.cpp:98
QCString pathListSeparator()
Definition portable.cpp:384
bool checkForExecutable(const QCString &fileName)
Definition portable.cpp:424
void unlink(const QCString &fileName)
Definition portable.cpp:545
const char * ghostScriptCommand()
Definition portable.cpp:438
FILE * fopen(const QCString &fileName, const QCString &mode)
Definition portable.cpp:350
uint32_t pid()
Definition portable.cpp:249
int pclose(FILE *stream)
Definition portable.cpp:489
size_t recodeUtf8StringToW(const QCString &inputStr, uint16_t **buf)
Definition portable.cpp:624
bool fileSystemIsCaseSensitive()
Definition portable.cpp:471
int system(const QCString &command, const QCString &args, bool commandHasConsole=true)
Definition portable.cpp:106
void setenv(const QCString &variable, const QCString &value)
Definition portable.cpp:287
void unsetenv(const QCString &variable)
Definition portable.cpp:302
const char * commandExtension()
Definition portable.cpp:462
const char * strnstr(const char *haystack, const char *needle, size_t haystack_len)
Definition portable.cpp:601
QCString getenv(const QCString &variable)
Definition portable.cpp:322
const char * devNull()
Definition portable.cpp:615
int fclose(FILE *f)
Definition portable.cpp:370
void setShortDir()
Definition portable.cpp:554
static bool ExistsOnPath(const QCString &fileName)
Definition portable.cpp:393
static bool environmentLoaded
Definition portable.cpp:38
static std::map< std::string, std::string > proc_env
Definition portable.cpp:39
static const char * portable_memmem(const char *haystack, size_t haystack_len, const char *needle, size_t needle_len)
Definition portable.cpp:573
char ** environ
void loadEnvironment()
Definition portable.cpp:261
Portable versions of functions that are platform dependent.
int portable_iconv_close(void *cd)
size_t portable_iconv(void *cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft)
void * portable_iconv_open(const char *tocode, const char *fromcode)
QCString substitute(const QCString &s, const QCString &src, const QCString &dst)
substitute all occurrences of src in s by dst
Definition qcstring.cpp:477
#define TRUE
Definition qcstring.h:37
#define FALSE
Definition qcstring.h:34
std::chrono::steady_clock::time_point startTime
Definition portable.cpp:78
A bunch of utility functions.