GCC Code Coverage Report


Directory: ./
File: basic/process_unix.cpp
Date: 2026-11-30 05:45:57
Exec Total Coverage
Lines: 45 122 36.9%
Functions: 10 21 47.6%
Branches: 8 73 11.0%

Line Branch Exec Source
1 /*
2 * Copyright (c) 2000-2022 Inria
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * * Neither the name of the ALICE Project-Team nor the names of its
14 * contributors may be used to endorse or promote products derived from this
15 * software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 *
29 * Contact: Bruno Levy
30 *
31 * https://www.inria.fr/fr/bruno-levy
32 *
33 * Inria,
34 * Domaine de Voluceau,
35 * 78150 Le Chesnay - Rocquencourt
36 * FRANCE
37 *
38 */
39
40 #include <geogram/basic/common.h>
41
42 #ifdef GEO_OS_UNIX
43
44 #include <geogram/basic/process.h>
45 #include <geogram/basic/process_private.h>
46 #include <geogram/basic/logger.h>
47 #include <geogram/basic/progress.h>
48 #include <geogram/basic/line_stream.h>
49
50 #include <sstream>
51 #include <pthread.h>
52 #include <unistd.h>
53 #include <limits.h>
54 #include <fenv.h>
55 #include <sys/types.h>
56 #include <sys/stat.h>
57 #include <sys/time.h>
58 #include <sys/resource.h>
59 #include <unistd.h>
60 #include <signal.h>
61 #include <fcntl.h>
62 #include <string.h>
63 #include <stdio.h>
64 #include <new>
65
66 // MUSL does not have execinfo (so we won't have backtrace with MUSL)
67 // Android declares backtrace() only from API level 33.
68 #if defined(__has_include)
69 #if __has_include(<execinfo.h>) && (!defined(__ANDROID__) || __ANDROID_API__ >= 33)
70 #include <execinfo.h>
71 #define HAS_EXECINFO
72 #endif
73 #endif
74
75 // detect MUSL that does not have feenableexcepts()/desisableexcepts()
76 #ifdef __linux__
77 #ifndef _GNU_SOURCE
78 #define _GNU_SOURCE
79 #include <features.h>
80 #ifndef __USE_GNU
81 #define __MUSL__
82 #endif
83 #undef _GNU_SOURCE
84 #else
85 #include <features.h>
86 #ifndef __USE_GNU
87 #define __MUSL__
88 #endif
89 #endif
90 #endif
91
92 #ifdef GEO_OS_APPLE
93 #include <mach-o/dyld.h>
94 #ifdef __x86_64
95 #include <xmmintrin.h>
96 #endif
97 #endif
98
99 #ifdef GEO_OS_EMSCRIPTEN
100 #include <emscripten.h>
101 #include <emscripten/threading.h>
102 #endif
103
104 #ifndef GEO_TBB
105 #define GEO_USE_PTHREAD_MANAGER
106 #endif
107
108 // Suppresses a warning with CLANG when sigaction is used.
109 #if defined(__clang__)
110 #pragma clang diagnostic ignored "-Wunknown-pragmas"
111 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
112 #endif
113
114 namespace {
115
116 using namespace GEO;
117
118 #ifdef GEO_OS_ANDROID
119
120 /**
121 * \brief Get the number of cores under Android
122 * \retval the number of cores if the request succeeds
123 * \retval -1 otherwise
124 * \internal
125 * sysconf(_SC_NPROCESSORS_ONLN) and sysconf(_SC_NPROCESSORS_CONF)
126 * is bugged under Android, see:
127 * https://code.google.com/p/android/issues/detail?id=26490
128 */
129 int android_get_number_of_cores() {
130 FILE* fp;
131 int res, i = -1, j = -1;
132 /* open file */
133 fp = fopen("/sys/devices/system/cpu/present", "r");
134 if(fp == 0) {
135 return -1; /* failure */
136 }
137
138 /* read and interpret line */
139 res = fscanf(fp, "%d-%d", &i, &j);
140
141 /* close file */
142 fclose(fp);
143
144 /* interpret result */
145 if(res == 1 && i == 0) {
146 /* single-core */
147 return 1;
148 }
149
150 if(res == 2 && i == 0) {
151 /* 2+ cores */
152 return j + 1;
153 }
154
155 return -1; /* failure */
156 }
157
158 #endif
159
160 #ifdef GEO_USE_PTHREAD_MANAGER
161
162 /**
163 * \brief POSIX Thread ThreadManager
164 * \details
165 * PThreadManager is an implementation of ThreadManager that uses POSIX
166 * threads for running concurrent threads and control critical sections.
167 */
168 class GEOGRAM_API PThreadManager : public ThreadManager {
169 public:
170 /**
171 * \brief Creates and initializes the POSIX ThreadManager
172 */
173 256 PThreadManager() {
174 256 pthread_attr_init(&attr_);
175 256 pthread_attr_setdetachstate(&attr_, PTHREAD_CREATE_JOINABLE);
176 256 }
177
178 /** \copydoc GEO::ThreadManager::maximum_concurrent_threads() */
179 6027 index_t maximum_concurrent_threads() override {
180 6027 return Process::number_of_cores();
181 }
182
183
184 protected:
185 /** \brief PThreadManager destructor */
186 1024 ~PThreadManager() override {
187 512 pthread_attr_destroy(&attr_);
188 1024 }
189
190 /**
191 * \brief Pthread_create callback for running a thread
192 * \details This function is passed a void pointer \p thread to a
193 * Thread and invokes the Thread function run().
194 * \param[in] thread_in void pointer to the Thread to be executed.
195 * \return always null pointer.
196 * \see Thread::run()
197 */
198 24586 static void* run_thread(void* thread_in) {
199 Thread* thread = reinterpret_cast<Thread*>(thread_in);
200 // Sets the thread-local-storage instance pointer, so
201 // that Thread::current() can retrieve it.
202 set_current_thread(thread);
203 24586 thread->run();
204 24586 return nullptr;
205 }
206
207 /** \copydoc GEO::ThreadManager::run_concurrent_threads() */
208 6027 void run_concurrent_threads (
209 ThreadGroup& threads, index_t max_threads
210 ) override {
211 // TODO: take max_threads into account
212 geo_argused(max_threads);
213
214
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 6027 times.
6027 thread_impl_.resize(threads.size());
215
2/2
✓ Branch 0 taken 24586 times.
✓ Branch 1 taken 6027 times.
61226 for(index_t i = 0; i < threads.size(); i++) {
216 Thread* T = threads[i];
217 set_thread_id(T,i);
218 24586 pthread_create(
219 24586 &thread_impl_[i], &attr_, &run_thread, T
220 );
221 }
222
2/2
✓ Branch 0 taken 24586 times.
✓ Branch 1 taken 6027 times.
55199 for(index_t i = 0; i < threads.size(); ++i) {
223 24586 pthread_join(thread_impl_[i], nullptr);
224 }
225
226 6027 }
227
228 private:
229 pthread_attr_t attr_;
230 std::vector<pthread_t> thread_impl_;
231 };
232
233 #endif
234
235 /**
236 * \brief Abnormal termination handler
237 * \details If \p message is
238 * non null, the following message is printed before exiting.
239 * <em>Abnormal program termination: message</em>
240 * \param[in] message optional message to print
241 */
242 GEO_NORETURN_DECL void abnormal_program_termination(
243 const char* message = nullptr
244 ) GEO_NORETURN;
245
246 ✗ void abnormal_program_termination(const char* message) {
247 ✗ if(message != nullptr) {
248 // Do not use Logger here!
249 std::cout
250 << "Abnormal program termination: "
251 ✗ << message << std::endl;
252 }
253 ✗ exit(1);
254 }
255
256 /**
257 * \brief Signal handler
258 * \details The handler exits the application
259 * \param[in] signal signal number
260 */
261 GEO_NORETURN_DECL void signal_handler(int signal) GEO_NORETURN;
262
263 ✗ void signal_handler(int signal) {
264 ✗ const char* sigstr = strsignal(signal);
265 ✗ std::ostringstream os;
266 ✗ os << "received signal " << signal << " (" << sigstr << ")";
267 ✗ Process::os_print_stack_trace();
268 ✗ abnormal_program_termination(os.str().c_str());
269 ✗ }
270
271 /**
272 * \brief Floating point error handler
273 * \details The handler exits the application
274 * \param[in] signal signal number
275 * \param[in] si signal information structure
276 * \param[in] data additional data (unused)
277 */
278 GEO_NORETURN_DECL void fpe_signal_handler(
279 int signal, siginfo_t* si, void* data
280 ) GEO_NORETURN;
281
282 ✗ void fpe_signal_handler(int signal, siginfo_t* si, void* data) {
283 geo_argused(signal);
284 geo_argused(data);
285 const char* error;
286 ✗ switch(si->si_code) {
287 case FPE_INTDIV:
288 error = "integer divide by zero";
289 break;
290 ✗ case FPE_INTOVF:
291 error = "integer overflow";
292 ✗ break;
293 ✗ case FPE_FLTDIV:
294 error = "floating point divide by zero";
295 ✗ break;
296 ✗ case FPE_FLTOVF:
297 error = "floating point overflow";
298 ✗ break;
299 ✗ case FPE_FLTUND:
300 error = "floating point underflow";
301 ✗ break;
302 ✗ case FPE_FLTRES:
303 error = "floating point inexact result";
304 ✗ break;
305 ✗ case FPE_FLTINV:
306 error = "floating point invalid operation";
307 ✗ break;
308 ✗ case FPE_FLTSUB:
309 error = "subscript out of range";
310 ✗ break;
311 ✗ default:
312 error = "unknown";
313 ✗ break;
314 }
315
316 ✗ std::ostringstream os;
317 ✗ os << "floating point exception detected: " << error;
318 ✗ abnormal_program_termination(os.str().c_str());
319 }
320
321 /**
322 * \brief Interrupt signal handler
323 * \details The handler cancels the current task if any or exits the
324 * program.
325 */
326 ✗ void sigint_handler(int) {
327 ✗ if(Progress::current_progress_task() != nullptr) {
328 ✗ Progress::cancel();
329 } else {
330 ✗ exit(1);
331 }
332 ✗ }
333
334 /**
335 * \brief Catches uncaught C++ exceptions
336 */
337 GEO_NORETURN_DECL void terminate_handler() GEO_NORETURN;
338
339 ✗ void terminate_handler() {
340 ✗ abnormal_program_termination("function terminate() was called");
341 }
342
343 /**
344 * \brief Catches allocation errors
345 */
346 GEO_NORETURN_DECL void memory_exhausted_handler() GEO_NORETURN;
347
348 ✗ void memory_exhausted_handler() {
349 ✗ abnormal_program_termination("memory exhausted");
350 }
351 }
352
353 /****************************************************************************/
354
355 namespace GEO {
356
357 namespace Process {
358
359 256 bool os_init_threads() {
360 #ifdef GEO_USE_PTHREAD_MANAGER
361
1/2
✓ Branch 2 taken 256 times.
✗ Branch 3 not taken.
256 Logger::out("Process")
362 << "Using posix threads"
363 << std::endl;
364 256 set_thread_manager(new PThreadManager);
365 256 return true;
366 #else
367 return false;
368 #endif
369 }
370
371 ✗ void os_brute_force_kill() {
372 ✗ kill(getpid(), SIGKILL);
373 ✗ }
374
375 256 index_t os_number_of_cores() {
376 #if defined(GEO_OS_ANDROID)
377 int nb_cores = android_get_number_of_cores();
378 geo_assert(nb_cores > 0);
379 return index_t(nb_cores);
380 #elif defined(GEO_OS_EMSCRIPTEN)
381 # ifdef __EMSCRIPTEN_PTHREADS__
382 return index_t(emscripten_num_logical_cores());
383 # else
384 return 1;
385 # endif
386 #else
387 256 return index_t(sysconf(_SC_NPROCESSORS_ONLN));
388 #endif
389 }
390
391 ✗ size_t os_used_memory() {
392 #ifdef GEO_OS_APPLE
393 size_t result = 0;
394 struct rusage usage;
395 if(0 == getrusage(RUSAGE_SELF, &usage)) {
396 result = (size_t) usage.ru_maxrss;
397 }
398 return result;
399 #else
400 // The following method seems to be more
401 // reliable than getrusage() under Linux.
402 // It works for both Linux and Android.
403 size_t result = 0;
404 ✗ LineInput in("/proc/self/status");
405 ✗ while(!in.eof() && in.get_line()) {
406 ✗ in.get_fields();
407 ✗ if(in.field_matches(0,"VmSize:")) {
408 ✗ result = size_t(in.field_as_uint(1)) * size_t(1024);
409 ✗ break;
410 }
411 }
412 ✗ return result;
413
414 /*
415 const char* statm_path = "/proc/self/statm";
416 unsigned long size,resident,share,text,lib,data,dt;
417 FILE *F = fopen(statm_path,"r");
418 if(F == nullptr) {
419 perror(statm_path);
420 abort();
421 }
422 if(
423 fscanf(F,"%ld %ld %ld %ld %ld %ld %ld",
424 &size,&resident,&share,&text,&lib,&data,&dt
425 ) != 7
426 ) {
427 perror(statm_path);
428 abort();
429 }
430 fclose(f);
431 */
432 #endif
433 ✗ }
434
435 ✗ size_t os_max_used_memory() {
436 // The following method seems to be more
437 // reliable than getrusage() under Linux.
438 // It works for both Linux and Android.
439 size_t result = 0;
440 ✗ LineInput in("/proc/self/status");
441
442 // Some versions of Unix may not have the proc
443 // filesystem (or a different organization)
444 ✗ if(!in.OK()) {
445 return result;
446 }
447
448 ✗ while(!in.eof() && in.get_line()) {
449 ✗ in.get_fields();
450 ✗ if(in.field_matches(0,"VmPeak:")) {
451 ✗ result = size_t(in.field_as_uint(1)) * size_t(1024);
452 ✗ break;
453 }
454 }
455 return result;
456 ✗ }
457
458 254 bool os_enable_FPE(bool flag) {
459 #if defined(GEO_OS_APPLE) || defined(GEO_OS_EMSCRIPTEN) || defined(__MUSL__)
460 geo_argused(flag);
461 #else
462 int excepts = 0
463 // | FE_INEXACT // inexact result
464 | FE_DIVBYZERO // division by zero
465 | FE_UNDERFLOW // result not representable due to underflow
466 | FE_OVERFLOW // result not representable due to overflow
467 | FE_INVALID // invalid operation
468 ;
469
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 254 times.
254 if(flag) {
470 ✗ feenableexcept(excepts);
471 } else {
472 254 fedisableexcept(excepts);
473 }
474 #endif
475 254 return true;
476 }
477
478 256 bool os_enable_cancel(bool flag) {
479
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 256 times.
256 if(flag) {
480 ✗ signal(SIGINT, sigint_handler);
481 } else {
482 256 signal(SIGINT, SIG_DFL);
483 }
484 256 return true;
485 }
486
487 /**
488 * \brief Installs signal handlers
489 * \details
490 * On Unix, this installs handlers for the standard signals.
491 * On Windows, this also installs all kind of exception handling
492 * routines that prevent the application from being blocked by a bad
493 * assertion, a runtime check or runtime error.
494 */
495 254 void os_install_signal_handlers() {
496 // Install signal handlers
497 254 signal(SIGSEGV, signal_handler);
498 254 signal(SIGILL, signal_handler);
499 254 signal(SIGBUS, signal_handler);
500
501 // Use sigaction for SIGFPE as it provides more details
502 // about the error.
503 struct sigaction sa, old_sa;
504 254 sa.sa_flags = SA_SIGINFO;
505 254 sa.sa_sigaction = fpe_signal_handler;
506 254 sigemptyset(&sa.sa_mask);
507 254 sigaction(SIGFPE, &sa, &old_sa);
508
509 // Install uncaught c++ exception handlers
510 254 std::set_terminate(terminate_handler);
511
512 // Install memory allocation handler
513 254 std::set_new_handler(memory_exhausted_handler);
514 254 }
515
516
517 /**
518 * \brief Gets the full path to the current executable.
519 */
520 ✗ std::string os_executable_filename() {
521 char buff[PATH_MAX];
522 #ifdef GEO_OS_APPLE
523 uint32_t len=PATH_MAX;
524 if (_NSGetExecutablePath(buff, &len) == 0) {
525 std::string filename(buff);
526 size_t pos = std::string::npos;
527 while( (pos=filename.find("/./")) != std::string::npos ) {
528 filename.replace(pos, 3, "/");
529 }
530 return filename;
531 }
532 return std::string("");
533 #else
534 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
535 ✗ if (len != -1) {
536 ✗ buff[len] = '\0';
537 ✗ return std::string(buff);
538 }
539 ✗ return std::string("");
540 #endif
541 }
542
543 ✗ void os_print_stack_trace() {
544 #ifdef HAS_EXECINFO
545 constexpr int MAX_STACK_FRAMES=128;
546 static void *stack_traces[MAX_STACK_FRAMES];
547 int i, trace_size = 0;
548 char **messages = nullptr;
549 ✗ trace_size = backtrace(stack_traces, MAX_STACK_FRAMES);
550 ✗ messages = backtrace_symbols(stack_traces, trace_size);
551 ✗ for (i = 0; i < trace_size; ++i) {
552 ✗ fprintf(stderr,"Stacktrace: %s\n",messages[i]);
553 }
554 ✗ if (messages != nullptr) {
555 ✗ free(messages);
556 }
557 #else
558 fprintf(stderr,"Stacktrace not available on platform\n");
559 #endif
560 ✗ }
561 }
562
563 }
564
565 #else
566
567 // Declare a dummy variable so that
568 // MSVC does not complain that it
569 // generated an empty object file.
570 int dummy_process_unix_compiled = 1;
571
572 #endif
573