LCOV - code coverage report
Current view: top level - source/lib/sysdep/os/unix - unix.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 10 124 8.1 %
Date: 2026-12-03 01:19:39 Functions: 1 12 8.3 %

          Line data    Source code
       1             : /* Copyright (c) 2026 Wildfire Games.
       2             :  *
       3             :  * Permission is hereby granted, free of charge, to any person obtaining
       4             :  * a copy of this software and associated documentation files (the
       5             :  * "Software"), to deal in the Software without restriction, including
       6             :  * without limitation the rights to use, copy, modify, merge, publish,
       7             :  * distribute, sublicense, and/or sell copies of the Software, and to
       8             :  * permit persons to whom the Software is furnished to do so, subject to
       9             :  * the following conditions:
      10             :  *
      11             :  * The above copyright notice and this permission notice shall be included
      12             :  * in all copies or substantial portions of the Software.
      13             :  *
      14             :  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
      15             :  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
      16             :  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
      17             :  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      18             :  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
      19             :  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
      20             :  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      21             :  */
      22             : 
      23             : #include "precompiled.h"
      24             : 
      25             : #include "lib/code_annotation.h"
      26             : #include "lib/debug.h"
      27             : #include "lib/os_path.h"
      28             : #include "lib/posix/posix_types.h"
      29             : #include "lib/secure_crt.h"
      30             : #include "lib/status.h"
      31             : #include "lib/sysdep/os.h"
      32             : #include "lib/sysdep/os/unix/udbg.h"
      33             : #include "lib/sysdep/sysdep.h"
      34             : #include "lib/utf8.h"
      35             : 
      36             : #include <boost/algorithm/string/replace.hpp>
      37             : #include <cstdio>
      38             : #include <cstdlib>
      39             : #include <cstring>
      40             : #include <string>
      41             : 
      42             : #define GNU_SOURCE
      43             : 
      44             : #include <sys/wait.h>
      45             : 
      46             : #if OS_MACOSX
      47             : #define URL_OPEN_COMMAND "open"
      48             : #else
      49             : #define URL_OPEN_COMMAND "xdg-open"
      50             : #endif
      51             : 
      52           0 : bool sys_IsDebuggerPresent()
      53             : {
      54           0 :     return false;
      55             : }
      56             : 
      57           0 : std::wstring sys_WideFromArgv(const char* argv_i)
      58             : {
      59             :     // argv is usually UTF-8 on Linux, unsure about OS X..
      60           0 :     return wstring_from_utf8(argv_i);
      61             : }
      62             : 
      63             : // these are basic POSIX-compatible backends for the sysdep.h functions.
      64             : // Win32 has better versions which override these.
      65             : 
      66           0 : void sys_display_msg(const wchar_t* caption, const wchar_t* msg)
      67             : {
      68           0 :     fprintf(stderr, "%ls: %ls\n", caption, msg); // must not use fwprintf, since stderr is byte-oriented
      69           0 : }
      70             : 
      71             : #if OS_MACOSX || OS_ANDROID
      72             : static ErrorReactionInternal try_gui_display_error(const wchar_t* /*text*/, bool /*manual_break*/,
      73             :     bool /*allow_suppress*/, bool /*no_continue*/)
      74             : {
      75             :     // TODO: implement this, in a way that doesn't rely on X11
      76             :     // and doesn't occasionally cause crazy errors like
      77             :     // "The process has forked and you cannot use this
      78             :     // CoreFoundation functionality safely. You MUST exec()."
      79             : 
      80             :     return ERI_NOT_IMPLEMENTED;
      81             : }
      82             : #else
      83           0 : static ErrorReactionInternal try_gui_display_error(const wchar_t* text, bool manual_break, bool allow_suppress, bool no_continue)
      84             : {
      85             :     // We'll run xmessage via fork/exec.
      86             :     // To avoid bad interaction between fork and pthreads, the child process
      87             :     // should only call async-signal-safe functions before exec.
      88             :     // So prepare all the child's data in advance, before forking:
      89             : 
      90           0 :     Status err; // ignore UTF-8 errors
      91           0 :     std::string message = utf8_from_wstring(text, &err);
      92             : 
      93             :     // Replace CRLF->LF
      94           0 :     boost::algorithm::replace_all(message, "\r\n", "\n");
      95             : 
      96             :     // TODO: we ought to wrap the text if it's very long,
      97             :     // since xmessage doesn't do that and it'll get clamped
      98             :     // to the screen width
      99             : 
     100           0 :     const char* cmd = "/usr/bin/xmessage";
     101             : 
     102           0 :     char buttons[256] = "";
     103           0 :     const char* defaultButton = "Exit";
     104             : 
     105           0 :     if(!no_continue)
     106             :     {
     107           0 :         strcat_s(buttons, sizeof(buttons), "Continue:100,");
     108             :         defaultButton = "Continue";
     109             :     }
     110             : 
     111           0 :     if(allow_suppress)
     112           0 :         strcat_s(buttons, sizeof(buttons), "Suppress:101,");
     113             : 
     114           0 :     strcat_s(buttons, sizeof(buttons), "Break:102,Debugger:103,Exit:104");
     115             : 
     116             :     // Since execv wants non-const strings, we strdup them all here
     117             :     // and will clean them up later (except in the child process where
     118             :     // memory leaks don't matter)
     119           0 :     char* const argv[] = {
     120           0 :         strdup(cmd),
     121           0 :         strdup("-geometry"), strdup("x500"), // set height so the box will always be very visible
     122           0 :         strdup("-title"), strdup("0 A.D. message"), // TODO: maybe shouldn't hard-code app name
     123           0 :         strdup("-buttons"), strdup(buttons),
     124           0 :         strdup("-default"), strdup(defaultButton),
     125           0 :         strdup(message.c_str()),
     126             :         NULL
     127           0 :     };
     128             : 
     129           0 :     pid_t cpid = fork();
     130           0 :     if(cpid == -1)
     131             :     {
     132           0 :         for(char* const* a = argv; *a; ++a)
     133           0 :             free(*a);
     134             :         return ERI_NOT_IMPLEMENTED;
     135             :     }
     136             : 
     137           0 :     if(cpid == 0)
     138             :     {
     139             :         // This is the child process
     140             : 
     141             :         // Set ASCII charset, to avoid font warnings from xmessage
     142           0 :         setenv("LC_ALL", "C", 1);
     143             : 
     144             :         // NOTE: setenv is not async-signal-safe, so we shouldn't really use
     145             :         // it here (it might want some mutex that was held by another thread
     146             :         // in the parent process and that will never be freed within this
     147             :         // process). But setenv/getenv are not guaranteed reentrant either,
     148             :         // and this error-reporting function might get called from a non-main
     149             :         // thread, so we can't just call setenv before forking as it might
     150             :         // break the other threads. And we can't just clone environ manually
     151             :         // inside the parent thread and use execve, because other threads might
     152             :         // be calling setenv and will break our iteration over environ.
     153             :         // In the absence of a good easy solution, and given that this is only
     154             :         // an error-reporting function and shouldn't get called frequently,
     155             :         // we'll just do setenv after the fork and hope that it fails
     156             :         // extremely rarely.
     157             : 
     158           0 :         execv(cmd, argv);
     159             : 
     160             :         // If exec returns, it failed
     161             :         //fprintf(stderr, "Error running %s: %d\n", cmd, errno);
     162           0 :         exit(-1);
     163             :     }
     164             : 
     165             :     // This is the parent process
     166             : 
     167             :     // Avoid memory leaks
     168           0 :     for(char* const* a = argv; *a; ++a)
     169           0 :         free(*a);
     170             : 
     171           0 :     int status = 0;
     172           0 :     waitpid(cpid, &status, 0);
     173             : 
     174             :     // If it didn't exist successfully, fall back to the non-GUI prompt
     175           0 :     if(!WIFEXITED(status))
     176             :         return ERI_NOT_IMPLEMENTED;
     177             : 
     178           0 :     switch(WEXITSTATUS(status))
     179             :     {
     180           0 :     case 103: // Debugger
     181           0 :         udbg_launch_debugger();
     182           0 :         [[fallthrough]];
     183             : 
     184           0 :     case 102: // Break
     185           0 :         if(manual_break)
     186             :             return ERI_BREAK;
     187           0 :         debug_break();
     188             :         return ERI_CONTINUE;
     189             : 
     190           0 :     case 100: // Continue
     191           0 :         if(!no_continue)
     192             :             return ERI_CONTINUE;
     193             :         // continue isn't allowed, so this was invalid input.
     194             :         return ERI_NOT_IMPLEMENTED;
     195             : 
     196           0 :     case 101: // Suppress
     197           0 :         if(allow_suppress)
     198             :             return ERI_SUPPRESS;
     199             :         // suppress isn't allowed, so this was invalid input.
     200             :         return ERI_NOT_IMPLEMENTED;
     201             : 
     202           0 :     case 104: // Exit
     203           0 :         abort();
     204             :         return ERI_EXIT;    // placebo; never reached
     205             : 
     206             :     }
     207             : 
     208             :     // Unexpected return value - fall back to the non-GUI prompt
     209             :     return ERI_NOT_IMPLEMENTED;
     210           0 : }
     211             : #endif
     212             : 
     213           0 : ErrorReactionInternal sys_display_error(const wchar_t* text, size_t flags)
     214             : {
     215           0 :     debug_printf("%s\n\n", utf8_from_wstring(text).c_str());
     216             : 
     217           0 :     const bool manual_break   = (flags & DE_MANUAL_BREAK  ) != 0;
     218           0 :     const bool allow_suppress = (flags & DE_ALLOW_SUPPRESS) != 0;
     219           0 :     const bool no_continue    = (flags & DE_NO_CONTINUE   ) != 0;
     220             : 
     221             :     // Try the GUI prompt if possible
     222           0 :     ErrorReactionInternal ret = try_gui_display_error(text, manual_break, allow_suppress, no_continue);
     223           0 :     if (ret != ERI_NOT_IMPLEMENTED)
     224             :         return ret;
     225             : 
     226             : #if OS_ANDROID
     227             :     // Android has no easy way to get user input here,
     228             :     // so continue or exit automatically
     229             :     if(no_continue)
     230             :         abort();
     231             :     else
     232             :         return ERI_CONTINUE;
     233             : #else
     234             :     // Otherwise fall back to the terminal-based input
     235             : 
     236             :     // Loop until valid input given:
     237           0 :     for(;;)
     238             :     {
     239           0 :         if(!no_continue)
     240           0 :             printf("(C)ontinue, ");
     241           0 :         if(allow_suppress)
     242           0 :             printf("(S)uppress, ");
     243           0 :         printf("(B)reak, Launch (D)ebugger, or (E)xit?\n");
     244             :         // TODO Should have some kind of timeout here.. in case you're unable to
     245             :         // access the controlling terminal (As might be the case if launched
     246             :         // from an xterm and in full-screen mode)
     247           0 :         int c = getchar();
     248             :         // note: don't use tolower because it'll choke on EOF
     249           0 :         switch(c)
     250             :         {
     251           0 :         case EOF:
     252           0 :         case 'd': case 'D':
     253           0 :             udbg_launch_debugger();
     254           0 :             [[fallthrough]];
     255             : 
     256           0 :         case 'b': case 'B':
     257           0 :             if(manual_break)
     258             :                 return ERI_BREAK;
     259           0 :             debug_break();
     260           0 :             return ERI_CONTINUE;
     261             : 
     262           0 :         case 'c': case 'C':
     263           0 :             if(!no_continue)
     264             :                 return ERI_CONTINUE;
     265             :             // continue isn't allowed, so this was invalid input. loop again.
     266             :             break;
     267           0 :         case 's': case 'S':
     268           0 :             if(allow_suppress)
     269             :                 return ERI_SUPPRESS;
     270             :             // suppress isn't allowed, so this was invalid input. loop again.
     271             :             break;
     272             : 
     273           0 :         case 'e': case 'E':
     274           0 :             abort();
     275             :             return ERI_EXIT;    // placebo; never reached
     276             :         }
     277             :     }
     278             : #endif
     279             : }
     280             : 
     281             : 
     282           0 : Status sys_StatusDescription(int /*err*/, wchar_t* /*buf*/, size_t /*max_chars*/)
     283             : {
     284             :     // don't need to do anything: lib/errors.cpp already queries
     285             :     // libc's strerror(). if we ever end up needing translation of
     286             :     // e.g. Qt or X errors, that'd go here.
     287           0 :     return ERR::FAIL;
     288             : }
     289             : 
     290             : // note: just use the sector size: Linux aio doesn't really care about
     291             : // the alignment of buffers/lengths/offsets, so we'll just pick a
     292             : // sane value and not bother scanning all drives.
     293           0 : size_t sys_max_sector_size()
     294             : {
     295             :     // users may call us more than once, so cache the results.
     296           0 :     static size_t cached_sector_size;
     297           0 :     if(!cached_sector_size)
     298           0 :         cached_sector_size = sysconf(_SC_PAGE_SIZE);
     299           0 :     return cached_sector_size;
     300             : }
     301             : 
     302           0 : std::wstring sys_get_user_name()
     303             : {
     304             :     // Prefer LOGNAME, fall back on getlogin
     305             : 
     306           0 :     const char* logname = getenv("LOGNAME");
     307           0 :     if (logname && strcmp(logname, "") != 0)
     308           0 :         return std::wstring(logname, logname + strlen(logname));
     309             :     // TODO: maybe we should do locale conversion?
     310             : 
     311             : #if OS_ANDROID
     312             : #warning TODO: sys_get_user_name: do something more appropriate and more thread-safe
     313             :     char* buf = getlogin();
     314             :     if (buf)
     315             :         return std::wstring(buf, buf + strlen(buf));
     316             : #else
     317           0 :     char buf[256];
     318           0 :     if (getlogin_r(buf, ARRAY_SIZE(buf)) == 0)
     319           0 :         return std::wstring(buf, buf + strlen(buf));
     320             : #endif
     321             : 
     322           0 :     return L"";
     323             : }
     324             : 
     325           2 : Status sys_generate_random_bytes(std::uint8_t* buf, size_t count)
     326             : {
     327           2 :     FILE* f = fopen("/dev/urandom", "rb");
     328           2 :     if (!f)
     329           0 :         WARN_RETURN(ERR::FAIL);
     330             : 
     331           4 :     while (count)
     332             :     {
     333           2 :         size_t numread = fread(buf, 1, count, f);
     334           2 :         if (numread == 0)
     335             :         {
     336           0 :             fclose(f);
     337           0 :             WARN_RETURN(ERR::FAIL);
     338             :         }
     339           2 :         buf += numread;
     340           2 :         count -= numread;
     341             :     }
     342             : 
     343           2 :     fclose(f);
     344             : 
     345           2 :     return INFO::OK;
     346             : }
     347             : 
     348           0 : Status sys_get_proxy_config(const std::wstring& /*url*/, std::wstring& /*proxy*/)
     349             : {
     350           0 :     return INFO::SKIPPED;
     351             : }
     352             : 
     353           0 : Status sys_open_url(const std::string& url)
     354             : {
     355           0 :     pid_t pid = fork();
     356           0 :     if (pid < 0)
     357             :     {
     358           0 :         debug_warn(L"Fork failed");
     359           0 :         return ERR::FAIL;
     360             :     }
     361           0 :     else if (pid == 0)
     362             :     {
     363             :         // we are the child
     364             : 
     365           0 :         execlp(URL_OPEN_COMMAND, URL_OPEN_COMMAND, url.c_str(), (const char*)NULL);
     366             : 
     367           0 :         debug_printf("Failed to run '" URL_OPEN_COMMAND "' command\n");
     368             : 
     369             :         // We can't call exit() because that'll try to free resources which were the parent's,
     370             :         // so just abort here
     371           0 :         abort();
     372             :     }
     373             :     else
     374             :     {
     375             :         // we are the parent
     376             : 
     377             :         // TODO: maybe we should wait for the child and make sure it succeeded
     378             : 
     379             :         return INFO::OK;
     380             :     }
     381             : }
     382             : 
     383           0 : FILE* sys_OpenFile(const OsPath& pathname, const char* mode)
     384             : {
     385           0 :     return fopen(OsString(pathname).c_str(), mode);
     386             : }

Generated by: LCOV version 1.16