1 /*
2  * Copyright (C) 2019 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 "gtest/gtest.h"
18 
19 #include <cinttypes>
20 #include <optional>
21 #include <tuple>
22 
23 #include "berberis/base/bit_util.h"
24 
25 #pragma clang diagnostic push
26 // Clang does not allow use of C++ types in “extern "C"” functions - but we need to declare one to
27 // test it.
28 #pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
29 
30 extern "C" std::tuple<uint64_t> AsmTupleTest(std::tuple<uint64_t>*);
31 
32 // This function takes first parameter %rdi and uses it as the address of a tuple.
33 // If tuple is returned on registers it would contain address of a tuple passed via pointer.
34 // If tuple is returned on stack this would be address of the returned tuple (hidden parameter).
35 asm(R"(.p2align 4, 0x90
36        .type AsmTupleTest,@function
37        AsmTupleTest:
38        .cfi_startproc
39        movl $42, (%rdi)
40        movq %rdi, %rax
41        ret
42        .size AsmTupleTest, .-AsmTupleTest
43        .cfi_endproc)");
44 
45 #pragma clang diagnostic pop
46 
47 namespace berberis {
48 
49 namespace {
50 
TupleIsReturnedOnRegisters()51 std::optional<bool> TupleIsReturnedOnRegisters() {
52   std::tuple<uint64_t> result_if_on_regs{};
53   std::tuple<uint64_t> result_if_on_stack{};
54   result_if_on_stack = AsmTupleTest(&result_if_on_regs);
55   if (std::get<uint64_t>(result_if_on_regs) == 42 &&
56       std::get<uint64_t>(result_if_on_stack) == bit_cast<uint64_t>(&result_if_on_regs)) {
57     return true;
58   } else if (std::get<uint64_t>(result_if_on_regs) == 0 &&
59              std::get<uint64_t>(result_if_on_stack) == 42) {
60     return false;
61   } else {
62     // Shouldn't happen with proper x86-64 compiler.
63     return {};
64   }
65 }
66 
67 // Note: tuple is returned on registers when libc++ is used and on stack if libstdc++ is used.
TEST(LibCxxAbi,Tuple)68 TEST(LibCxxAbi, Tuple) {
69   auto tuple_is_returned_on_registers = TupleIsReturnedOnRegisters();
70   EXPECT_TRUE(tuple_is_returned_on_registers.has_value());
71 #ifdef _LIBCPP_VERSION
72   EXPECT_TRUE(*tuple_is_returned_on_registers);
73 #else
74   EXPECT_FALSE(*tuple_is_returned_on_registers);
75 #endif
76 }
77 
78 }  // namespace
79 
80 }  // namespace berberis
81