gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/syscalls/linux/getrandom.cc (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #include <sys/syscall.h> 16 #include <sys/types.h> 17 #include <unistd.h> 18 19 #include "gtest/gtest.h" 20 #include "test/util/test_util.h" 21 22 namespace gvisor { 23 namespace testing { 24 25 namespace { 26 27 #ifndef SYS_getrandom 28 #if defined(__x86_64__) 29 #define SYS_getrandom 318 30 #elif defined(__i386__) 31 #define SYS_getrandom 355 32 #elif defined(__aarch64__) 33 #define SYS_getrandom 278 34 #else 35 #error "Unknown architecture" 36 #endif 37 #endif // SYS_getrandom 38 39 bool SomeByteIsNonZero(char* random_bytes, int length) { 40 for (int i = 0; i < length; i++) { 41 if (random_bytes[i] != 0) { 42 return true; 43 } 44 } 45 return false; 46 } 47 48 TEST(GetrandomTest, IsRandom) { 49 // This test calls get_random and makes sure that the array is filled in with 50 // something that is non-zero. Perhaps we get back \x00\x00\x00\x00\x00.... as 51 // a random result, but it's so unlikely that we'll just ignore this. 52 char random_bytes[64] = {}; 53 int n = syscall(SYS_getrandom, random_bytes, 64, 0); 54 SKIP_IF(!IsRunningOnGvisor() && n < 0 && errno == ENOSYS); 55 EXPECT_THAT(n, SyscallSucceeds()); 56 EXPECT_GT(n, 0); // Some bytes should be returned. 57 EXPECT_TRUE(SomeByteIsNonZero(random_bytes, n)); 58 } 59 60 } // namespace 61 62 } // namespace testing 63 } // namespace gvisor