aboutsummaryrefslogtreecommitdiff
path: root/test_common/harness/os_helpers.cpp
blob: 8fc911083bbf6d907147344bc7449dd425b65eee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//
// Copyright (c) 2017 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "os_helpers.h"
#include "errorHelpers.h"

// =================================================================================================
// C++ interface.
// =================================================================================================

#include <cerrno> // errno, error constants
#include <climits> // PATH_MAX
#include <cstdlib> // abort, _splitpath, _makepath
#include <cstring> // strdup, strerror_r
#include <sstream>

#include <vector>

#if defined(__ANDROID__)
#include <android/api-level.h>
#endif

#define CHECK_PTR(ptr)                                                         \
    if ((ptr) == NULL)                                                         \
    {                                                                          \
        abort();                                                               \
    }

typedef std::vector<char> buffer_t;

#if !defined(PATH_MAX)
#define PATH_MAX 1000
#endif

int const _size = PATH_MAX + 1; // Initial buffer size for path.
int const _count = 8; // How many times we will try to double buffer size.

// -------------------------------------------------------------------------------------------------
// MacOS X
// -------------------------------------------------------------------------------------------------

#if defined(__APPLE__)


#include <mach-o/dyld.h> // _NSGetExecutablePath
#include <libgen.h> // dirname


static std::string
_err_msg(int err, // Error number (e. g. errno).
         int level // Nesting level, for avoiding infinite recursion.
)
{

    /*
        There are 3 incompatible versions of strerror_r:

            char * strerror_r( int, char *, size_t );  // GNU version
            int    strerror_r( int, char *, size_t );  // BSD version
            int    strerror_r( int, char *, size_t );  // XSI version

        BSD version returns error code, while XSI version returns 0 or -1 and
       sets errno.

    */

    // BSD version of strerror_r.
    buffer_t buffer(100);
    int count = _count;
    for (;;)
    {
        int rc = strerror_r(err, &buffer.front(), buffer.size());
        if (rc == EINVAL)
        {
            // Error code is not recognized, but anyway we got the message.
            return &buffer.front();
        }
        else if (rc == ERANGE)
        {
            // Buffer is not enough.
            if (count > 0)
            {
                // Enlarge the buffer.
                --count;
                buffer.resize(buffer.size() * 2);
            }
            else
            {
                std::stringstream ostr;
                ostr << "Error " << err << " "
                     << "(Getting error message failed: "
                     << "Buffer of " << buffer.size()
                     << " bytes is still too small"
                     << ")";
                return ostr.str();
            }; // if
        }
        else if (rc == 0)
        {
            // We got the message.
            return &buffer.front();
        }
        else
        {
            std::stringstream ostr;
            ostr << "Error " << err << " "
                 << "(Getting error message failed: "
                 << (level < 2 ? _err_msg(rc, level + 1) : "Oops") << ")";
            return ostr.str();
        }; // if
    }; // forever

} // _err_msg


std::string dir_sep() { return "/"; } // dir_sep


std::string exe_path()
{
    buffer_t path(_size);
    int count = _count;
    for (;;)
    {
        uint32_t size = path.size();
        int rc = _NSGetExecutablePath(&path.front(), &size);
        if (rc == 0)
        {
            break;
        }; // if
        if (count > 0)
        {
            --count;
            path.resize(size);
        }
        else
        {
            log_error("ERROR: Getting executable path failed: "
                      "_NSGetExecutablePath failed: Buffer of %lu bytes is "
                      "still too small\n",
                      (unsigned long)path.size());
            exit(2);
        }; // if
    }; // forever
    return &path.front();
} // exe_path


std::string exe_dir()
{
    std::string path = exe_path();
    // We cannot pass path.c_str() to `dirname' bacause `dirname' modifies its
    // argument.
    buffer_t buffer(path.c_str(),
                    path.c_str() + path.size() + 1); // Copy with trailing zero.
    return dirname(&buffer.front());
} // exe_dir


#endif // __APPLE__

// -------------------------------------------------------------------------------------------------
// Linux
// -------------------------------------------------------------------------------------------------

#if defined(__linux__)


#include <cerrno> // errno
#include <libgen.h> // dirname
#include <unistd.h> // readlink


static std::string _err_msg(int err, int level)
{

    /*
        There are 3 incompatible versions of strerror_r:

            char * strerror_r( int, char *, size_t );  // GNU version
            int    strerror_r( int, char *, size_t );  // BSD version
            int    strerror_r( int, char *, size_t );  // XSI version

        BSD version returns error code, while XSI version returns 0 or -1 and
       sets errno.

    */

#if (defined(__ANDROID__) && __ANDROID_API__ < 23)                             \
    || ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE)

// XSI version of strerror_r.
#warning Not tested!
    buffer_t buffer(200);
    int count = _count;
    for (;;)
    {
        int rc = strerror_r(err, &buffer.front(), buffer.size());
        if (rc == -1)
        {
            int _err = errno;
            if (_err == ERANGE)
            {
                if (count > 0)
                {
                    // Enlarge the buffer.
                    --count;
                    buffer.resize(buffer.size() * 2);
                }
                else
                {
                    std::stringstream ostr;
                    ostr << "Error " << err << " "
                         << "(Getting error message failed: "
                         << "Buffer of " << buffer.size()
                         << " bytes is still too small"
                         << ")";
                    return ostr.str();
                }; // if
            }
            else
            {
                std::stringstream ostr;
                ostr << "Error " << err << " "
                     << "(Getting error message failed: "
                     << (level < 2 ? _err_msg(_err, level + 1) : "Oops") << ")";
                return ostr.str();
            }; // if
        }
        else
        {
            // We got the message.
            return &buffer.front();
        }; // if
    }; // forever

#else

    // GNU version of strerror_r.
    char buffer[2000];
    return strerror_r(err, buffer, sizeof(buffer));

#endif

} // _err_msg


std::string dir_sep() { return "/"; } // dir_sep


std::string exe_path()
{

    static std::string const exe = "/proc/self/exe";

    buffer_t path(_size);
    int count = _count; // Max number of iterations.

    for (;;)
    {

        ssize_t len = readlink(exe.c_str(), &path.front(), path.size());

        if (len < 0)
        {
            // Oops.
            int err = errno;
            log_error("ERROR: Getting executable path failed: "
                      "Reading symlink `%s' failed: %s\n",
                      exe.c_str(), err_msg(err).c_str());
            exit(2);
        }; // if

        if (len < path.size())
        {
            // We got the path.
            path.resize(len);
            break;
        }; // if

        // Oops, buffer is too small.
        if (count > 0)
        {
            --count;
            // Enlarge the buffer.
            path.resize(path.size() * 2);
        }
        else
        {
            log_error("ERROR: Getting executable path failed: "
                      "Reading symlink `%s' failed: Buffer of %lu bytes is "
                      "still too small\n",
                      exe.c_str(), (unsigned long)path.size());
            exit(2);
        }; // if

    }; // forever

    return std::string(&path.front(), path.size());

} // exe_path


std::string exe_dir()
{
    std::string path = exe_path();
    // We cannot pass path.c_str() to `dirname' bacause `dirname' modifies its
    // argument.
    buffer_t buffer(path.c_str(),
                    path.c_str() + path.size() + 1); // Copy with trailing zero.
    return dirname(&buffer.front());
} // exe_dir

#endif // __linux__

// -------------------------------------------------------------------------------------------------
// MS Windows
// -------------------------------------------------------------------------------------------------

#if defined(_WIN32)


#include <windows.h>

#include <cctype>
#include <algorithm>


static std::string _err_msg(int err, int level)
{

    std::string msg;

    LPSTR buffer = NULL;
    DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
        | FORMAT_MESSAGE_IGNORE_INSERTS;

    DWORD len = FormatMessageA(flags, NULL, err, LANG_USER_DEFAULT,
                               reinterpret_cast<LPSTR>(&buffer), 0, NULL);

    if (buffer == NULL || len == 0)
    {

        int _err = GetLastError();
        char str[1024] = { 0 };
        snprintf(str, sizeof(str),
                 "Error 0x%08x (Getting error message failed: %s )", err,
                 (level < 2 ? _err_msg(_err, level + 1).c_str() : "Oops"));
        msg = std::string(str);
    }
    else
    {

        // Trim trailing whitespace (including `\r' and `\n').
        while (len > 0 && isspace(buffer[len - 1]))
        {
            --len;
        }; // while

        // Drop trailing full stop.
        if (len > 0 && buffer[len - 1] == '.')
        {
            --len;
        }; // if

        msg.assign(buffer, len);

    }; // if

    if (buffer != NULL)
    {
        LocalFree(buffer);
    }; // if

    return msg;

} // _get_err_msg


std::string dir_sep() { return "\\"; } // dir_sep


std::string exe_path()
{

    buffer_t path(_size);
    int count = _count;

    for (;;)
    {

        DWORD len = GetModuleFileNameA(NULL, &path.front(),
                                       static_cast<DWORD>(path.size()));

        if (len == 0)
        {
            int err = GetLastError();
            log_error("ERROR: Getting executable path failed: %s\n",
                      err_msg(err).c_str());
            exit(2);
        }; // if

        if (len < path.size())
        {
            path.resize(len);
            break;
        }; // if

        // Buffer too small.
        if (count > 0)
        {
            --count;
            path.resize(path.size() * 2);
        }
        else
        {
            log_error("ERROR: Getting executable path failed: "
                      "Buffer of %lu bytes is still too small\n",
                      (unsigned long)path.size());
            exit(2);
        }; // if

    }; // forever

    return std::string(&path.front(), path.size());

} // exe_path


std::string exe_dir()
{

    std::string exe = exe_path();
    int count = 0;

    // Splitting path into components.
    buffer_t drv(_MAX_DRIVE);
    buffer_t dir(_MAX_DIR);
    count = _count;
#if defined(_MSC_VER)
    for (;;)
    {
        int rc =
            _splitpath_s(exe.c_str(), &drv.front(), drv.size(), &dir.front(),
                         dir.size(), NULL, 0, // We need neither name
                         NULL, 0 // nor extension
            );
        if (rc == 0)
        {
            break;
        }
        else if (rc == ERANGE)
        {
            if (count > 0)
            {
                --count;
                // Buffer is too small, but it is not clear which one.
                // So we have to enlarge all.
                drv.resize(drv.size() * 2);
                dir.resize(dir.size() * 2);
            }
            else
            {
                log_error("ERROR: Getting executable path failed: "
                          "Splitting path `%s' to components failed: "
                          "Buffers of %lu and %lu bytes are still too small\n",
                          exe.c_str(), (unsigned long)drv.size(),
                          (unsigned long)dir.size());
                exit(2);
            }; // if
        }
        else
        {
            log_error("ERROR: Getting executable path failed: "
                      "Splitting path `%s' to components failed: %s\n",
                      exe.c_str(), err_msg(rc).c_str());
            exit(2);
        }; // if
    }; // forever

#else // __MINGW32__

    // MinGW does not have the "secure" _splitpath_s, use the insecure version
    // instead.
    _splitpath(exe.c_str(), &drv.front(), &dir.front(),
               NULL, // We need neither name
               NULL // nor extension
    );
#endif // __MINGW32__

    // Combining components back to path.
    // I failed with "secure" `_makepath_s'. If buffer is too small, instead of
    // returning ERANGE, `_makepath_s' pops up dialog box and offers to debug
    // the program. D'oh! So let us try to guess the size of result and go with
    // insecure `_makepath'.
    buffer_t path(std::max(drv.size() + dir.size(), size_t(_MAX_PATH)) + 10);
    _makepath(&path.front(), &drv.front(), &dir.front(), NULL, NULL);

    return &path.front();

} // exe_dir


#endif // _WIN32


std::string err_msg(int err) { return _err_msg(err, 0); } // err_msg


// =================================================================================================
// C interface.
// =================================================================================================


char* get_err_msg(int err)
{
    char* msg = strdup(err_msg(err).c_str());
    CHECK_PTR(msg);
    return msg;
} // get_err_msg


char* get_dir_sep()
{
    char* sep = strdup(dir_sep().c_str());
    CHECK_PTR(sep);
    return sep;
} // get_dir_sep


char* get_exe_path()
{
    char* path = strdup(exe_path().c_str());
    CHECK_PTR(path);
    return path;
} // get_exe_path


char* get_exe_dir()
{
    char* dir = strdup(exe_dir().c_str());
    CHECK_PTR(dir);
    return dir;
} // get_exe_dir


// end of file //