1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <dlfcn.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <sys/mount.h>
22 #include <sys/stat.h>
23 
24 #include <cstdio>
25 #include <cstring>
26 
27 #include <android/log.h>
28 
29 #include "NativeBridgeTest.h"
30 
31 namespace android {
32 
TEST_F(NativeBridgeTest,PreInitializeNativeBridge)33 TEST_F(NativeBridgeTest, PreInitializeNativeBridge) {
34     ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
35 #if !defined(__APPLE__)         // Mac OS does not support bind-mount.
36 #if !defined(__ANDROID__)       // Cannot write into the hard-wired location.
37     static constexpr const char* kTestData = "PreInitializeNativeBridge test.";
38 
39     // Try to create our mount namespace.
40     if (unshare(CLONE_NEWNS) != -1) {
41         // Create a placeholder file.
42         FILE* cpuinfo = fopen("./cpuinfo", "w");
43         ASSERT_NE(nullptr, cpuinfo) << strerror(errno);
44         fprintf(cpuinfo, kTestData);
45         fclose(cpuinfo);
46 
47         ASSERT_TRUE(PreInitializeNativeBridge("does not matter 1", "short 2"));
48 
49         // Read /proc/cpuinfo
50         FILE* proc_cpuinfo = fopen("/proc/cpuinfo", "r");
51         ASSERT_NE(nullptr, proc_cpuinfo) << strerror(errno);
52         char buf[1024];
53         EXPECT_NE(nullptr, fgets(buf, sizeof(buf), proc_cpuinfo)) << "Error reading.";
54         fclose(proc_cpuinfo);
55 
56         EXPECT_EQ(0, strcmp(buf, kTestData));
57 
58         // Delete the file.
59         ASSERT_EQ(0, unlink("./cpuinfo")) << "Error unlinking temporary file.";
60         // Ending the test will tear down the mount namespace.
61     } else {
62         GTEST_LOG_(WARNING) << "Could not create mount namespace. Are you running this as root?";
63     }
64 #endif
65 #endif
66 }
67 
68 }  // namespace android
69