1 // Copyright 2021 Code Intelligence GmbH
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 "jvm_tooling.h"
16
17 #include <memory>
18
19 #include "gtest/gtest.h"
20 #include "tools/cpp/runfiles/runfiles.h"
21
22 #ifdef _WIN32
23 #define ARG_SEPARATOR ";"
24 #else
25 #define ARG_SEPARATOR ":"
26 #endif
27
28 namespace jazzer {
29
30 class JvmToolingTest : public ::testing::Test {
31 protected:
32 // After DestroyJavaVM() no new JVM instance can be created in the same
33 // process, so we set up a single JVM instance for this test binary which gets
34 // destroyed after all tests in this test suite have finished.
SetUpTestCase()35 static void SetUpTestCase() {
36 FLAGS_jvm_args =
37 "-Denv1=va\\" ARG_SEPARATOR "l1\\\\" ARG_SEPARATOR "-Denv2=val2";
38 using ::bazel::tools::cpp::runfiles::Runfiles;
39 std::unique_ptr<Runfiles> runfiles(Runfiles::CreateForTest());
40 FLAGS_cp = runfiles->Rlocation(
41 "jazzer/launcher/testdata/fuzz_target_mocks_deploy.jar");
42
43 jvm_ = std::unique_ptr<JVM>(new JVM());
44 }
45
TearDownTestCase()46 static void TearDownTestCase() { jvm_.reset(nullptr); }
47
48 static std::unique_ptr<JVM> jvm_;
49 };
50
51 std::unique_ptr<JVM> JvmToolingTest::jvm_ = nullptr;
52
TEST_F(JvmToolingTest,JniProperties)53 TEST_F(JvmToolingTest, JniProperties) {
54 auto &env = jvm_->GetEnv();
55 auto property_printer_class = env.FindClass("test/PropertyPrinter");
56 ASSERT_NE(nullptr, property_printer_class);
57 auto method_id =
58 env.GetStaticMethodID(property_printer_class, "printProperty",
59 "(Ljava/lang/String;)Ljava/lang/String;");
60 ASSERT_NE(nullptr, method_id);
61
62 for (const auto &el : std::vector<std::pair<std::string, std::string>>{
63 {"not set property", ""},
64 {"env1", "va" ARG_SEPARATOR "l1\\"},
65 {"env2", "val2"}}) {
66 jstring str = env.NewStringUTF(el.first.c_str());
67 auto ret = (jstring)env.CallStaticObjectMethod(property_printer_class,
68 method_id, str);
69 ASSERT_FALSE(env.ExceptionCheck());
70 if (el.second.empty()) {
71 ASSERT_EQ(nullptr, ret);
72 } else {
73 ASSERT_NE(nullptr, ret);
74 jboolean is_copy;
75 ASSERT_EQ(el.second, env.GetStringUTFChars(ret, &is_copy));
76 }
77 }
78 }
79 } // namespace jazzer
80