LCOV - code coverage report
Current view: top level - source/lib - secure_crt.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 54 54 100.0 %
Date: 2026-12-03 01:19:39 Functions: 9 14 64.3 %

          Line data    Source code
       1             : /* Copyright (C) 2025 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             : /*
      24             :  * partial implementation of VC8's secure CRT functions
      25             :  */
      26             : 
      27             : #include "precompiled.h"
      28             : 
      29             : #include "secure_crt.h"
      30             : 
      31             : #include "lib/code_generation.h"
      32             : #include "lib/debug.h"
      33             : 
      34             : #include <algorithm>
      35             : #include <cerrno>
      36             : #include <cinttypes>
      37             : #include <cstdarg>
      38             : #include <cstdio>
      39             : 
      40             : #if OS_ANDROID
      41             : # include <boost/algorithm/string/replace.hpp>
      42             : #endif
      43             : 
      44             : // we were included from wsecure_crt.cpp; skip all stuff that
      45             : // must only be done once.
      46             : #ifndef WSECURE_CRT
      47             : static const StatusDefinition secureCrtStatusDefinitions[] = {
      48             :     { ERR::STRING_NOT_TERMINATED, L"Invalid string (no 0 terminator found in buffer)" }
      49             : };
      50             : STATUS_ADD_DEFINITIONS(secureCrtStatusDefinitions);
      51             : #endif
      52             : 
      53             : 
      54             : // written against http://std.dkuug.dk/jtc1/sc22/wg14/www/docs/n1031.pdf .
      55             : // optimized for size - e.g. strcpy calls strncpy with n = SIZE_MAX.
      56             : 
      57             : // since char and wide versions of these functions are basically the same,
      58             : // this source file implements generic versions and bridges the differences
      59             : // with these macros. wsecure_crt.cpp #defines WSECURE_CRT and
      60             : // includes this file.
      61             : 
      62             : // Note: These defines are all #undef:ed at the end of the file - remember to
      63             : // add a corresponding #undef when adding a #define.
      64             : #ifdef WSECURE_CRT
      65             : # define tchar wchar_t
      66             : # define tstring std::wstring
      67             : # define T(string_literal) L ## string_literal
      68             : # define tnlen_s wcsnlen_s
      69             : # define tncpy_s wcsncpy_s
      70             : # define tcpy_s wcscpy_s
      71             : # define tncat_s wcsncat_s
      72             : # define tcat_s wcscat_s
      73             : # define tcmp wcscmp
      74             : # define tcpy wcscpy
      75             : # define tvsnprintf vswprintf   // used by implementation
      76             : # define tvsprintf_s vswprintf_s
      77             : # define tsprintf_s swprintf_s
      78             : #else
      79             : # define tchar char
      80             : # define tstring std::string
      81             : # define T(string_literal) string_literal
      82             : # define tnlen_s strnlen_s
      83             : # define tncpy_s strncpy_s
      84             : # define tcpy_s strcpy_s
      85             : # define tncat_s strncat_s
      86             : # define tcat_s strcat_s
      87             : # define tcmp strcmp
      88             : # define tcpy strcpy
      89             : # define tvsnprintf vsnprintf   // used by implementation
      90             : # define tvsprintf_s vsprintf_s
      91             : # define tsprintf_s sprintf_s
      92             : #endif  // #ifdef WSECURE_CRT
      93             : 
      94             : 
      95             : // return <retval> and raise an assertion if <condition> doesn't hold.
      96             : // usable as a statement.
      97             : #define ENFORCE(condition, err_to_warn, retval) STMT(\
      98             :     if(!(condition))                    \
      99             :     {                                   \
     100             :         DEBUG_WARN_ERR(err_to_warn);    \
     101             :         return retval;                  \
     102             :     }                                   \
     103             : )
     104             : 
     105             : // raise a debug warning if <len> is the size of a pointer.
     106             : // catches bugs such as: tchar* s = ..; tcpy_s(s, sizeof(s), T(".."));
     107             : // if warnings get annoying, replace with debug_printf. usable as a statement.
     108             : //
     109             : // currently disabled due to high risk of false positives.
     110             : #define WARN_IF_PTR_LEN(len)\
     111             : /*
     112             :     ENSURE(len != sizeof(char*));
     113             : */
     114             : 
     115             : 
     116             : // skip our implementation if already available, but not the
     117             : // self-test and the t* defines (needed for test).
     118             : #if EMULATE_SECURE_CRT
     119             : 
     120             : // return length [in characters] of a string, not including the trailing
     121             : // null character. to protect against access violations, only the
     122             : // first <max_len> characters are examined; if the null character is
     123             : // not encountered by then, <max_len> is returned.
     124          27 : size_t tnlen_s(const tchar* str, size_t max_len)
     125             : {
     126             :     // note: we can't bail - what would the return value be?
     127          27 :     ENSURE(str != 0);
     128             : 
     129          27 :     WARN_IF_PTR_LEN(max_len);
     130             : 
     131          27 :     size_t len;
     132          70 :     for(len = 0; len < max_len; len++)
     133          69 :         if(*str++ == '\0')
     134             :             break;
     135             : 
     136          27 :     return len;
     137             : }
     138             : 
     139             : #if OS_ANDROID
     140             : static tstring androidFormat(const tchar *fmt)
     141             : {
     142             :     // FIXME handle %%hs, %%ls, etc
     143             :     tstring ret(fmt);
     144             :     boost::algorithm::replace_all(ret, T("%ls"), T("%S"));
     145             :     boost::algorithm::replace_all(ret, T("%hs"), T("%s"));
     146             :     return ret;
     147             : }
     148             : #endif
     149             : 
     150             : // copy at most <max_src_chars> (not including trailing null) from
     151             : // <src> into <dst>, which must not overlap.
     152             : // if thereby <max_dst_chars> (including null) would be exceeded,
     153             : // <dst> is set to the empty string and ERANGE returned; otherwise,
     154             : // 0 is returned to indicate success and that <dst> is null-terminated.
     155             : //
     156             : // note: padding with zeroes is not called for by N1031.
     157       14685 : int tncpy_s(tchar* dst, size_t max_dst_chars, const tchar* src, size_t max_src_chars)
     158             : {
     159             :     // the MS implementation returns EINVAL and allows dst = 0 if
     160             :     // max_dst_chars = max_src_chars = 0. no mention of this in
     161             :     // 3.6.2.1.1, so don't emulate that behavior.
     162       14685 :     ENFORCE(dst != 0, ERR::INVALID_POINTER, EINVAL);
     163       14682 :     ENFORCE(max_dst_chars != 0, ERR::INVALID_SIZE, EINVAL); // N1031 says ERANGE, MSDN/MSVC says EINVAL
     164       14681 :     *dst = '\0';    // in case src ENFORCE is triggered
     165       14681 :     ENFORCE(src != 0, ERR::INVALID_POINTER, EINVAL);
     166             : 
     167       14679 :     WARN_IF_PTR_LEN(max_dst_chars);
     168       14679 :     WARN_IF_PTR_LEN(max_src_chars);
     169             : 
     170             :     // copy string until null character encountered or limit reached.
     171             :     // optimized for size (less comparisons than MS impl) and
     172             :     // speed (due to well-predicted jumps; we don't bother unrolling).
     173       14679 :     tchar* p = dst;
     174       14679 :     size_t chars_left = std::min(max_dst_chars, max_src_chars);
     175       73386 :     while(chars_left != 0)
     176             :     {
     177             :         // success: reached end of string normally.
     178       58719 :         if((*p++ = *src++) == '\0')
     179             :             return 0;
     180       58707 :         chars_left--;
     181             :     }
     182             : 
     183             :     // which limit did we hit?
     184             :     // .. dst, and last character wasn't null: overflow.
     185       14667 :     if(max_dst_chars <= max_src_chars)
     186             :     {
     187          16 :         *dst = '\0';
     188          16 :         ENFORCE(0, ERR::INVALID_SIZE, ERANGE);
     189             :     }
     190             :     // .. source: success, but still need to null-terminate the destination.
     191       14651 :     *p = '\0';
     192       14651 :     return 0;
     193             : }
     194             : 
     195             : 
     196             : // copy <src> (including trailing null) into <dst>, which must not overlap.
     197             : // if thereby <max_dst_chars> (including null) would be exceeded,
     198             : // <dst> is set to the empty string and ERANGE returned; otherwise,
     199             : // 0 is returned to indicate success and that <dst> is null-terminated.
     200          13 : int tcpy_s(tchar* dst, size_t max_dst_chars, const tchar* src)
     201             : {
     202          13 :     return tncpy_s(dst, max_dst_chars, src, SIZE_MAX);
     203             : }
     204             : 
     205             : 
     206             : // append <src> to <dst>, which must not overlap.
     207             : // if thereby <max_dst_chars> (including null) would be exceeded,
     208             : // <dst> is set to the empty string and ERANGE returned; otherwise,
     209             : // 0 is returned to indicate success and that <dst> is null-terminated.
     210          31 : int tncat_s(tchar* dst, size_t max_dst_chars, const tchar* src, size_t max_src_chars)
     211             : {
     212          31 :     ENFORCE(dst != 0, ERR::INVALID_POINTER, EINVAL);
     213          28 :     ENFORCE(max_dst_chars != 0, ERR::INVALID_SIZE, EINVAL); // N1031 says ERANGE, MSDN/MSVC says EINVAL
     214             :     // src is checked in tncpy_s
     215             : 
     216             :     // WARN_IF_PTR_LEN not necessary: both max_dst_chars and max_src_chars
     217             :     // are checked by tnlen_s / tncpy_s (respectively).
     218             : 
     219          27 :     const size_t dst_len = tnlen_s(dst, max_dst_chars);
     220          27 :     if(dst_len == max_dst_chars)
     221             :     {
     222           1 :         *dst = '\0';
     223           1 :         ENFORCE(0, ERR::STRING_NOT_TERMINATED, EINVAL); // N1031/MSDN says ERANGE, MSVC says EINVAL
     224             :     }
     225             : 
     226          26 :     tchar* const end = dst+dst_len;
     227          26 :     const size_t chars_left = max_dst_chars-dst_len;
     228          26 :     int ret = tncpy_s(end, chars_left, src, max_src_chars);
     229             :     // if tncpy_s overflowed, we need to clear the start of our string
     230             :     // (not just the appended part). can't do that by default, because
     231             :     // the beginning of dst is not changed in normal operation.
     232          26 :     if(ret != 0)
     233          11 :         *dst = '\0';
     234             :     return ret;
     235             : }
     236             : 
     237             : 
     238             : // append <src> to <dst>, which must not overlap.
     239             : // if thereby <max_dst_chars> (including null) would be exceeded,
     240             : // <dst> is set to the empty string and ERANGE returned; otherwise,
     241             : // 0 is returned to indicate success and that <dst> is null-terminated.
     242             : //
     243             : // note: implemented as tncat_s(dst, max_dst_chars, src, SIZE_MAX)
     244          16 : int tcat_s(tchar* dst, size_t max_dst_chars, const tchar* src)
     245             : {
     246          16 :     return tncat_s(dst, max_dst_chars, src, SIZE_MAX);
     247             : }
     248             : 
     249             : 
     250         612 : int tvsprintf_s(tchar* dst, size_t max_dst_chars, const tchar* fmt, va_list ap)
     251             : {
     252         612 :     if(!dst || !fmt || max_dst_chars == 0)
     253             :     {
     254           6 :         errno = EINVAL;
     255           6 :         return -1;
     256             :     }
     257             : 
     258             : #if OS_ANDROID
     259             :     // Workaround for https://code.google.com/p/android/issues/detail?id=109074
     260             :     // (vswprintf doesn't null-terminate strings)
     261             :     memset(dst, 0, max_dst_chars * sizeof(tchar));
     262             : 
     263             :     const int ret = tvsnprintf(dst, max_dst_chars, androidFormat(fmt).c_str(), ap);
     264             : #else
     265         606 :     const int ret = tvsnprintf(dst, max_dst_chars, fmt, ap);
     266             : #endif
     267         606 :     if(ret < 0 || ret >= int(max_dst_chars))  // not enough space
     268             :     {
     269           4 :         dst[0] = '\0';
     270           4 :         return -1;
     271             :     }
     272             :     return ret; // negative if error, else # chars written (excluding '\0')
     273             : }
     274             : 
     275             : 
     276         588 : int tsprintf_s(tchar* buf, size_t max_chars, const tchar* fmt, ...)
     277             : {
     278         588 :     va_list ap;
     279         588 :     va_start(ap, fmt);
     280         588 :     int len = tvsprintf_s(buf, max_chars, fmt, ap);
     281         588 :     va_end(ap);
     282         588 :     return len;
     283             : }
     284             : 
     285             : #endif // #if EMULATE_SECURE_CRT
     286             : 
     287             : #undef tchar
     288             : #undef T
     289             : #undef tnlen_s
     290             : #undef tncpy_s
     291             : #undef tcpy_s
     292             : #undef tncat_s
     293             : #undef tcat_s
     294             : #undef tcmp
     295             : #undef tcpy
     296             : #undef tvsnprintf
     297             : #undef tvsprintf_s
     298             : #undef tsprintf_s

Generated by: LCOV version 1.16