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 "NativeBridgeTest.h"
18
19#include <cstdio>
20#include <cstring>
21#include <cutils/log.h>
22#include <dlfcn.h>
23#include <errno.h>
24#include <fcntl.h>
25#include <stdio.h>
26#include <sys/mount.h>
27#include <sys/stat.h>
28
29namespace android {
30
31static constexpr const char* kTestData = "PreInitializeNativeBridge test.";
32
33TEST_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    // Try to create our mount namespace.
38    if (unshare(CLONE_NEWNS) != -1) {
39        // Create a dummy file.
40        FILE* cpuinfo = fopen("./cpuinfo", "w");
41        ASSERT_NE(nullptr, cpuinfo) << strerror(errno);
42        fprintf(cpuinfo, kTestData);
43        fclose(cpuinfo);
44
45        ASSERT_TRUE(PreInitializeNativeBridge("does not matter 1", "short 2"));
46
47        // Read /proc/cpuinfo
48        FILE* proc_cpuinfo = fopen("/proc/cpuinfo", "r");
49        ASSERT_NE(nullptr, proc_cpuinfo) << strerror(errno);
50        char buf[1024];
51        EXPECT_NE(nullptr, fgets(buf, sizeof(buf), proc_cpuinfo)) << "Error reading.";
52        fclose(proc_cpuinfo);
53
54        EXPECT_EQ(0, strcmp(buf, kTestData));
55
56        // Delete the file.
57        ASSERT_EQ(0, unlink("./cpuinfo")) << "Error unlinking temporary file.";
58        // Ending the test will tear down the mount namespace.
59    } else {
60        GTEST_LOG_(WARNING) << "Could not create mount namespace. Are you running this as root?";
61    }
62#endif
63#endif
64}
65
66}  // namespace android
67