Ubuntu Pastebin

Paste from chris at Mon, 6 Jul 2015 23:21:02 +0000

Download as text
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
 * Copyright © 2015 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Christopher James Halse Rogers <christopher.halse.rogers@canonical.com>
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <type_traits>
#include <functional>
#include <sys/mman.h>
#include <system_error>
#include <cstring>

namespace mir
{
template<typename Result, typename... Args>
class FunctionTrampoline
{
public:
    FunctionTrampoline(std::function<Result(Args...)> const& f)
        : holder(f)
    {
    }

    typedef Result (*raw_ptr)(Args...);

    raw_ptr as_c_call() const
    {
        return holder.as_c_call();
    }
    
private:
    class function_holder
    {
    public:
        function_holder(std::function<Result(Args...)> const& f)
            : f{f},
              invoker{std::mem_fn(&std::function<Result(Args...)>::operator())},
              trampoline(generate_trampoline())
        {

        }

        raw_ptr as_c_call() const
        {
            return reinterpret_cast<raw_ptr>(trampoline.get());
        }

    private:
        static constexpr uintptr_t function_object_guard{0xfffffffefffffffe};
        static constexpr uintptr_t function_member_guard{0xffffffdffffffffd};
        
        static Result c_call(Args... args)
        {
            std::function<Result(Args...)>* volatile f = reinterpret_cast<std::function<Result(Args...)>*>(function_object_guard);
            decltype(std::mem_fn(&std::function<Result(Args...)>::operator()))* volatile fn =
                reinterpret_cast<decltype(std::mem_fn(&std::function<Result(Args...)>::operator()))*>(function_member_guard);
            return (*fn)(*f, args...);
        }

        std::unique_ptr<char, void(*)(void*)> generate_trampoline()
        {
            const ssize_t pagesize{sysconf(_SC_PAGESIZE)};
            
            void* data;
            if (posix_memalign(&data, pagesize, pagesize) != 0)
            {
                throw std::system_error{errno, std::system_category(), "Failed to allocate page-aligned memory"};
            }

            std::unique_ptr<char, void(*)(void*)> trampoline{reinterpret_cast<char*>(data), &free};

            std::memcpy(trampoline.get(), (void*)&c_call, pagesize);

            for (char* start = trampoline.get(); start < trampoline.get() + pagesize; ++start)
            {
                if (*reinterpret_cast<uintptr_t*>(start) == function_object_guard)
                {
                    *reinterpret_cast<uintptr_t*>(start) = reinterpret_cast<uintptr_t const>(&f);
                }
                else if (*reinterpret_cast<uintptr_t*>(start) == function_member_guard)
                {
                    *reinterpret_cast<uintptr_t*>(start) = reinterpret_cast<uintptr_t const>(&invoker);
                }
            }

            if (mprotect(trampoline.get(), pagesize, PROT_EXEC) != 0)
            {
                throw std::system_error{errno, std::system_category(), "Failed to set mprotect"};
            }
            return trampoline;
        }
        
        std::function<Result(Args...)> const f;
        decltype(std::mem_fn(&std::function<Result(Args...)>::operator())) const invoker;
        std::unique_ptr<char, void (*)(void*)> const trampoline;
    } holder;
};
}

TEST(FunctionTrampoline, can_call_void_void_from_function_ptr)
{
    bool called{false};
    mir::FunctionTrampoline<void> trampoline{[&called]() { called = true; }};

    void (*decayed)();
    decayed = trampoline.as_c_call();
    (*decayed)();
    EXPECT_TRUE(called);

    int (*multiarg)(int, float);

    auto ctx = std::make_shared<int>(6);
    mir::FunctionTrampoline<int, int, float> t2{
        [ctx](int hello, float world)
        {
            return *ctx + hello + (int)world;
        }
    };

    multiarg = t2.as_c_call();

    EXPECT_THAT((*multiarg)(5, 5), testing::Eq(6 + 5 + 5));
}
Download as text