Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
560
561
562
563
#!/usr/bin/env python3
"""
Simulation test for the cpuinfo sysfs fallback fix.
 
This test verifies two fixes for https://github.com/microsoft/onnxruntime/issues/10038:
 
1. Safe logging in env.cc - PosixEnv constructor no longer crashes when the
   logging system is not yet initialized and cpuinfo_initialize() fails.
 
2. cpuinfo sysfs fallback - The patched cpuinfo library falls back to
   sysconf(_SC_NPROCESSORS_ONLN) for both processor counts and per-CPU
   present/possible flags when /sys/devices/system/cpu/{possible,present}
   files are missing.
 
Testing approach:
- Test 1: Compile a small C++ program that calls the safe logging pattern
  without a registered logger. Verify it doesn't crash.
- Test 2: Compile a small C program that validates the sysconf fallback
  arithmetic and verifies that the fallback marks each online CPU with both
  PRESENT and POSSIBLE flags. This catches the incomplete count-only fallback.
- Test 3: Use an LD_PRELOAD shim (like the lambda-arm64-onnx workaround)
  to simulate missing sysfs files and verify ORT loads without crash.
 
Note: Tests 2 and 3 require a build of ORT with the patches applied.
Test 1 can run standalone.
"""
 
import os
import shutil
import subprocess
import sys
import tempfile
import textwrap
import unittest
 
 
def _require_linux():
    if sys.platform != "linux":
        raise unittest.SkipTest("Test requires Linux")
 
 
def _require_gcc():
    if not shutil.which("gcc"):
        raise unittest.SkipTest("gcc not found")
 
 
def _require_gpp():
    if not shutil.which("g++"):
        raise unittest.SkipTest("g++ not found")
 
 
class TestCpuinfoSysfsFallback(unittest.TestCase):
    def test_safe_logging_pattern(self):
        """Verify the safe logging pattern doesn't crash when no logger exists.
 
        This simulates the fix in env.cc where we check HasDefaultLogger() before
        calling LOGS_DEFAULT(). We compile a minimal C++ program that:
        - Does NOT register a default logger
        - Calls the safe logging pattern
        - Verifies it writes to stderr instead of crashing
        """
        _require_linux()
        _require_gpp()
 
        source = textwrap.dedent(r"""
        #include <iostream>
        #include <string_view>
 
        // Minimal simulation of ORT's logging check pattern
        namespace logging {
        class LoggingManager {
        public:
            // Simulate: no default logger registered
            static bool HasDefaultLogger() { return false; }
        };
        }  // namespace logging
 
        void LogEarlyWarning(std::string_view message) {
            if (logging::LoggingManager::HasDefaultLogger()) {
                // Would call LOGS_DEFAULT(WARNING) here - but logger doesn't exist
                // This path should NOT be taken
                std::cerr << "BUG: should not reach here\n";
                return;
            }
            // Safe fallback to stderr
            std::cerr << "onnxruntime warning: " << message << "\n";
        }
 
        int main() {
            // This simulates what PosixEnv() does when cpuinfo_initialize() fails
            bool cpuinfo_available = false;  // Simulating failure
            if (!cpuinfo_available) {
                LogEarlyWarning("cpuinfo_initialize failed. "
                               "May cause CPU EP performance degradation due to undetected CPU features.");
            }
            std::cout << "PASS: Safe logging pattern works without crash\n";
            return 0;
        }
        """)
 
        with tempfile.NamedTemporaryFile(suffix=".cc", mode="w", delete=False) as f:
            f.write(source)
            src_path = f.name
 
        try:
            exe_path = src_path.replace(".cc", "")
            result = subprocess.run(
                ["g++", "-std=c++17", "-o", exe_path, src_path], check=False, capture_output=True, text=True
            )
            self.assertEqual(result.returncode, 0, f"Compilation failed: {result.stderr}")
 
            result = subprocess.run([exe_path], check=False, capture_output=True, text=True, timeout=10)
            self.assertEqual(
                result.returncode, 0, f"Program crashed with exit code {result.returncode}: {result.stderr}"
            )
            self.assertIn("PASS", result.stdout)
        finally:
            os.unlink(src_path)
            if os.path.exists(src_path.replace(".cc", "")):
                os.unlink(src_path.replace(".cc", ""))
 
    def test_sysconf_fallback(self):
        """Verify sysconf(_SC_NPROCESSORS_ONLN) works as a complete fallback.
 
        This doesn't test the actual cpuinfo patch (that requires building cpuinfo)
        but verifies the fallback mechanism produces correct counts and marks
        present/possible flags for each online CPU.
        """
        _require_linux()
        _require_gcc()
 
        source = textwrap.dedent(r"""
        #include <stdint.h>
        #include <stdio.h>
        #include <unistd.h>
 
        #define CPUINFO_LINUX_FLAG_PRESENT 0x1
        #define CPUINFO_LINUX_FLAG_POSSIBLE 0x2
 
        int main() {
            long nproc = sysconf(_SC_NPROCESSORS_ONLN);
            if (nproc <= 0) {
                printf("FAIL: sysconf(_SC_NPROCESSORS_ONLN) returned %ld\n", nproc);
                return 1;
            }
            // Simulate what the patched cpuinfo max-count helpers return:
            // max_processor = nproc - 1 (0-indexed). Then arm_linux_init does:
            // 1 + max_processor = nproc.
            unsigned int max_processor = (unsigned int)(nproc - 1);
            unsigned int arm_linux_processors_count = 1 + max_processor;
 
            uint32_t processor_flags[1024] = {0};
            unsigned int processors_count = arm_linux_processors_count;
            if (processors_count > 1024) {
                processors_count = 1024;
            }
 
            // Simulate cpuinfo_linux_detect_possible_processors() and
            // cpuinfo_linux_detect_present_processors() fallback helpers.
            for (unsigned int processor = 0; processor < processors_count; ++processor) {
                processor_flags[processor] |= CPUINFO_LINUX_FLAG_PRESENT;
                processor_flags[processor] |= CPUINFO_LINUX_FLAG_POSSIBLE;
            }
 
            unsigned int valid_processors = 0;
            const uint32_t valid_processor_mask = CPUINFO_LINUX_FLAG_PRESENT | CPUINFO_LINUX_FLAG_POSSIBLE;
            for (unsigned int processor = 0; processor < processors_count; ++processor) {
                if ((processor_flags[processor] & valid_processor_mask) == valid_processor_mask) {
                    ++valid_processors;
                }
            }
 
            printf("sysconf(_SC_NPROCESSORS_ONLN) = %ld\n", nproc);
            printf("Simulated max_processor = %u\n", max_processor);
            printf("Simulated arm_linux_processors_count = %u\n", arm_linux_processors_count);
            printf("Simulated valid_processors = %u\n", valid_processors);
 
            if (arm_linux_processors_count == (unsigned int)nproc && valid_processors == processors_count) {
                printf("PASS: Fallback produces correct processor count and flags\n");
                return 0;
            }
            printf("FAIL: Processor count or flags mismatch\n");
            return 1;
        }
        """)
 
        with tempfile.NamedTemporaryFile(suffix=".c", mode="w", delete=False) as f:
            f.write(source)
            src_path = f.name
 
        try:
            exe_path = src_path.replace(".c", "")
            result = subprocess.run(["gcc", "-o", exe_path, src_path], check=False, capture_output=True, text=True)
            self.assertEqual(result.returncode, 0, f"Compilation failed: {result.stderr}")
 
            result = subprocess.run([exe_path], check=False, capture_output=True, text=True, timeout=10)
            self.assertEqual(result.returncode, 0, f"exit code {result.returncode}: {result.stdout}")
            self.assertIn("PASS", result.stdout)
        finally:
            os.unlink(src_path)
            if os.path.exists(src_path.replace(".c", "")):
                os.unlink(src_path.replace(".c", ""))
 
    def test_sysfs_hide_with_ld_preload(self):
        """Verify LD_PRELOAD shim can hide sysfs files.
 
        This compiles a small shim that intercepts open-family calls to return
        ENOENT for /sys/devices/system/cpu/{possible,present}, then runs a test
        program that opens those files.
        """
        _require_linux()
        _require_gcc()
 
        shim_source = textwrap.dedent(r"""
        #define _GNU_SOURCE
        #include <dlfcn.h>
        #include <errno.h>
        #include <fcntl.h>
        #include <stdarg.h>
        #include <stdio.h>
        #include <string.h>
        #include <sys/types.h>
 
#ifndef O_TMPFILE
#define O_TMPFILE 0
#endif
 
        static const char *CPU_POSSIBLE = "/sys/devices/system/cpu/possible";
        static const char *CPU_PRESENT  = "/sys/devices/system/cpu/present";
 
        static int is_blocked(const char *path) {
            return (strcmp(path, CPU_POSSIBLE) == 0 || strcmp(path, CPU_PRESENT) == 0);
        }
 
        static mode_t get_mode_if_needed(int flags, va_list args) {
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE)) ? va_arg(args, mode_t) : 0;
        }
 
        int open(const char *path, int flags, ...) {
            static int (*real_open)(const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_open) real_open = dlsym(RTLD_NEXT, "open");
            if (is_blocked(path)) {
                errno = ENOENT;
                return -1;
            }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_open(path, flags, mode)
                       : real_open(path, flags);
        }
 
        int open64(const char *path, int flags, ...) {
            static int (*real_open64)(const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_open64) real_open64 = dlsym(RTLD_NEXT, "open64");
            if (is_blocked(path)) {
                errno = ENOENT;
                return -1;
            }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_open64(path, flags, mode)
                       : real_open64(path, flags);
        }
 
        int openat(int dirfd, const char *path, int flags, ...) {
            static int (*real_openat)(int, const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_openat) real_openat = dlsym(RTLD_NEXT, "openat");
            if (path && is_blocked(path)) {
                errno = ENOENT;
                return -1;
            }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_openat(dirfd, path, flags, mode)
                       : real_openat(dirfd, path, flags);
        }
 
        int openat64(int dirfd, const char *path, int flags, ...) {
            static int (*real_openat64)(int, const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_openat64) real_openat64 = dlsym(RTLD_NEXT, "openat64");
            if (path && is_blocked(path)) {
                errno = ENOENT;
                return -1;
            }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_openat64(dirfd, path, flags, mode)
                       : real_openat64(dirfd, path, flags);
        }
 
        FILE *fopen(const char *restrict path, const char *restrict mode) {
            static FILE *(*real_fopen)(const char *, const char *) = NULL;
            if (!real_fopen) real_fopen = dlsym(RTLD_NEXT, "fopen");
 
            if (is_blocked(path)) {
                errno = ENOENT;
                return NULL;
            }
            return real_fopen(path, mode);
        }
        """)
 
        test_source = textwrap.dedent(r"""
        #include <errno.h>
        #include <fcntl.h>
        #include <stdio.h>
        #include <string.h>
        #include <unistd.h>
 
        static int try_open(const char *path) {
            int fd = open(path, O_RDONLY);
            if (fd >= 0) {
                close(fd);
            }
            return fd;
        }
 
        int main() {
            int fd;
            int pass = 1;
 
            fd = try_open("/sys/devices/system/cpu/possible");
            if (fd >= 0) {
                printf("FAIL: /sys/devices/system/cpu/possible should be blocked\n");
                pass = 0;
            } else {
                printf("OK: /sys/devices/system/cpu/possible blocked (errno=%d: %s)\n",
                       errno, strerror(errno));
            }
 
            fd = try_open("/sys/devices/system/cpu/present");
            if (fd >= 0) {
                printf("FAIL: /sys/devices/system/cpu/present should be blocked\n");
                pass = 0;
            } else {
                printf("OK: /sys/devices/system/cpu/present blocked (errno=%d: %s)\n",
                       errno, strerror(errno));
            }
 
            // Verify other files still work
            fd = try_open("/proc/cpuinfo");
            if (fd < 0) {
                printf("WARN: /proc/cpuinfo not accessible (may be OK in some envs)\n");
            } else {
                printf("OK: /proc/cpuinfo still accessible\n");
            }
 
            if (pass) {
                printf("PASS: LD_PRELOAD sysfs-hiding shim works correctly\n");
            }
            return pass ? 0 : 1;
        }
        """)
 
        with tempfile.TemporaryDirectory() as tmpdir:
            shim_path = os.path.join(tmpdir, "hide_sysfs.c")
            shim_so = os.path.join(tmpdir, "hide_sysfs.so")
            test_path = os.path.join(tmpdir, "test_sysfs.c")
            test_exe = os.path.join(tmpdir, "test_sysfs")
 
            with open(shim_path, "w") as f:
                f.write(shim_source)
            with open(test_path, "w") as f:
                f.write(test_source)
 
            # Compile shim
            result = subprocess.run(
                ["gcc", "-shared", "-fPIC", "-o", shim_so, shim_path, "-ldl"],
                check=False,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, f"Shim compilation failed: {result.stderr}")
 
            # Compile test
            result = subprocess.run(["gcc", "-o", test_exe, test_path], check=False, capture_output=True, text=True)
            self.assertEqual(result.returncode, 0, f"Test compilation failed: {result.stderr}")
 
            # Run with LD_PRELOAD
            env = os.environ.copy()
            env["LD_PRELOAD"] = shim_so
            result = subprocess.run([test_exe], check=False, capture_output=True, text=True, timeout=10, env=env)
            self.assertEqual(result.returncode, 0, f"exit code {result.returncode}: {result.stdout}")
            self.assertIn("PASS", result.stdout)
 
    def test_ort_import_with_hidden_sysfs(self):
        """Integration test - import onnxruntime with hidden sysfs files.
 
        This uses the LD_PRELOAD shim to hide /sys/devices/system/cpu/{possible,present}
        and then imports onnxruntime. This is the actual end-to-end test that
        verifies both fixes work together.
 
        NOTE: This requires onnxruntime to be built with the patches applied.
        """
        _require_linux()
        _require_gcc()
 
        # Check if onnxruntime is importable
        result = subprocess.run(
            [sys.executable, "-c", "import onnxruntime"], check=False, capture_output=True, text=True, timeout=30
        )
        if result.returncode != 0:
            self.skipTest("onnxruntime not installed/importable")
 
        shim_source = textwrap.dedent(r"""
        #define _GNU_SOURCE
        #include <dlfcn.h>
        #include <errno.h>
        #include <fcntl.h>
        #include <stdarg.h>
        #include <stdio.h>
        #include <string.h>
        #include <sys/types.h>
 
#ifndef O_TMPFILE
#define O_TMPFILE 0
#endif
 
        static const char *CPU_POSSIBLE = "/sys/devices/system/cpu/possible";
        static const char *CPU_PRESENT  = "/sys/devices/system/cpu/present";
 
        static int is_blocked(const char *path) {
            return (strcmp(path, CPU_POSSIBLE) == 0 || strcmp(path, CPU_PRESENT) == 0);
        }
 
        static mode_t get_mode_if_needed(int flags, va_list args) {
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE)) ? va_arg(args, mode_t) : 0;
        }
 
        int open(const char *path, int flags, ...) {
            static int (*real_open)(const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_open) real_open = dlsym(RTLD_NEXT, "open");
            if (is_blocked(path)) { errno = ENOENT; return -1; }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_open(path, flags, mode)
                       : real_open(path, flags);
        }
 
        int open64(const char *path, int flags, ...) {
            static int (*real_open64)(const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_open64) real_open64 = dlsym(RTLD_NEXT, "open64");
            if (is_blocked(path)) { errno = ENOENT; return -1; }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_open64(path, flags, mode)
                       : real_open64(path, flags);
        }
 
        int openat(int dirfd, const char *path, int flags, ...) {
            static int (*real_openat)(int, const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_openat) real_openat = dlsym(RTLD_NEXT, "openat");
            if (path && is_blocked(path)) { errno = ENOENT; return -1; }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_openat(dirfd, path, flags, mode)
                       : real_openat(dirfd, path, flags);
        }
 
        int openat64(int dirfd, const char *path, int flags, ...) {
            static int (*real_openat64)(int, const char *, int, ...) = NULL;
            va_list args;
            mode_t mode = 0;
 
            if (!real_openat64) real_openat64 = dlsym(RTLD_NEXT, "openat64");
            if (path && is_blocked(path)) { errno = ENOENT; return -1; }
 
            va_start(args, flags);
            mode = get_mode_if_needed(flags, args);
            va_end(args);
            return ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE))
                       ? real_openat64(dirfd, path, flags, mode)
                       : real_openat64(dirfd, path, flags);
        }
 
        FILE *fopen(const char *restrict path, const char *restrict mode) {
            static FILE *(*real_fopen)(const char *, const char *) = NULL;
            if (!real_fopen) real_fopen = dlsym(RTLD_NEXT, "fopen");
            if (is_blocked(path)) { errno = ENOENT; return NULL; }
            return real_fopen(path, mode);
        }
        """)
 
        with tempfile.TemporaryDirectory() as tmpdir:
            shim_path = os.path.join(tmpdir, "hide_sysfs.c")
            shim_so = os.path.join(tmpdir, "hide_sysfs.so")
 
            with open(shim_path, "w") as f:
                f.write(shim_source)
 
            result = subprocess.run(
                ["gcc", "-shared", "-fPIC", "-o", shim_so, shim_path, "-ldl"],
                check=False,
                capture_output=True,
                text=True,
            )
            self.assertEqual(result.returncode, 0, f"Shim compilation failed: {result.stderr}")
 
            env = os.environ.copy()
            env["LD_PRELOAD"] = shim_so
 
            # Try importing onnxruntime with hidden sysfs
            ort_script = (
                "import onnxruntime; print('PASS: onnxruntime imported successfully'); "
                "print(f'Version: {onnxruntime.__version__}'); "
                "print(f'Providers: {onnxruntime.get_available_providers()}')"
            )
            result = subprocess.run(
                [sys.executable, "-c", ort_script],
                check=False,
                capture_output=True,
                text=True,
                timeout=60,
                env=env,
            )
            self.assertEqual(result.returncode, 0, f"exit code {result.returncode}: {result.stderr}")
            self.assertIn("PASS", result.stdout)
 
 
if __name__ == "__main__":
    unittest.main()