sgx_module.cc 6.54 KB
Newer Older
nhynes committed
1 2 3 4 5 6
/*!
 *  Copyright (c) 2018 by Contributors
 * \file sgx_module.cc
 * \brief SGX enclave module.
 */
#include <dmlc/logging.h>
nhynes committed
7
#include <sgx_urts.h>
nhynes committed
8
#include <tvm/runtime/c_runtime_api.h>
nhynes committed
9
#include <tvm/runtime/device_api.h>
nhynes committed
10 11 12 13 14 15 16 17 18 19 20
#include <tvm/runtime/registry.h>
#include <tvm/runtime/threading_backend.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <unordered_map>
#include "../common.h"
#include "../../file_util.h"
nhynes committed
21
#include "./tvm_u.h"
nhynes committed
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

namespace tvm {
namespace runtime {

class SGXModuleNode;

namespace sgx {

class EnclaveContext {
 public:
  explicit EnclaveContext(SGXModuleNode* mod) {
    CHECK(Context()->mod_ == nullptr)
      << "Tried overriding existing enclave context.";
    CHECK(mod != nullptr) << "Tried setting null enclave context.";
    Context()->mod_ = mod;
  }
  ~EnclaveContext() {
    Context()->mod_ = nullptr;
  }

  static SGXModuleNode* GetModule() {
    SGXModuleNode* ctx = Context()->mod_;
    CHECK(ctx != nullptr) << "No current enclave context";
    return ctx;
  }

 private:
  EnclaveContext() {}
  SGXModuleNode* mod_;

  static EnclaveContext* Context() {
    static thread_local EnclaveContext inst;
    return &inst;
  }
};

}  // namespace sgx

class SGXModuleNode : public ModuleNode {
 public:
  ~SGXModuleNode() {
    if (eid_) {
      sgx::EnclaveContext ctx(this);
      sgx_destroy_enclave(eid_);
    }
  }

  void Init(const std::string& enclave_file) {
    std::string token_file = GetCacheDir() + "/" +
                             GetFileBasename(enclave_file) + ".token";
    sgx_launch_token_t token = {0};
    int token_updated = 0;

    try {
      std::ifstream ifs(token_file, std::fstream::in | std::fstream::binary);
      ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
      ifs >> token;
    } catch (std::ifstream::failure e) {
      memset(&token, 0x0, sizeof(sgx_launch_token_t));
    }

    TVM_SGX_CHECKED_CALL(sgx_create_enclave(
        enclave_file.c_str(), SGX_DEBUG_FLAG, &token, &token_updated, &eid_, NULL));

    sgx::EnclaveContext ctx(this);
    TVMRetValue rv;
    TVM_SGX_CHECKED_CALL(tvm_ecall_init(eid_, &rv));

    if (!token_updated) return;

    try {
      std::ofstream ofs(token_file, std::fstream::trunc | std::fstream::binary);
      ofs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
      ofs << token;
    } catch (std::ifstream::failure e) {
      LOG(INFO) << "Could not save SGX launch token to " << token_file;
    }
  }

  const char* type_key() const final {
    return "sgx";
  }

  PackedFunc GetFunction(
      const std::string& name,
      const std::shared_ptr<ModuleNode>& sptr_to_self) final {
    auto exported = exports_.find(name);
    if (exported == exports_.end()) return PackedFunc();
    int func_id = exported->second;
    return PackedFunc([this, func_id](TVMArgs args, TVMRetValue* rv) {
        sgx::EnclaveContext ctx(this);
113 114
        TVMValue ret_value;
        int ret_type_code;
nhynes committed
115
        TVM_SGX_CHECKED_CALL(tvm_ecall_packed_func(eid_, func_id,
116 117
              args.values, args.type_codes, args.num_args, &ret_value, &ret_type_code));
        *rv = TVMArgValue(ret_value, ret_type_code);
nhynes committed
118 119 120
      });
  }

121 122
  void RunWorkers(int num_tasks) {
    std::function<void(int)> runner = [this](int _worker_id) {
nhynes committed
123
      this->GetFunction("__tvm_run_worker__",
124
                        std::shared_ptr<SGXModuleNode>(nullptr))();
nhynes committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    };
    thread_group_.reset(new tvm::runtime::threading::ThreadGroup(
          num_tasks, runner, false /* include_main_thread */));
  }

  void JoinThreads() {
    thread_group_->Join();
  }

  void RegisterExport(std::string name, int func_id) {
    exports_[name] = func_id;
  }

 private:
  // ID of the loaded enclave
  sgx_enclave_id_t eid_;
  // Names and IDs of functions exported by the enclave module
  std::unordered_map<std::string, int> exports_;
  std::unique_ptr<tvm::runtime::threading::ThreadGroup> thread_group_;
};

namespace sgx {

TVM_REGISTER_GLOBAL("__sgx_thread_group_launch__")
.set_body([](TVMArgs args, TVMRetValue* rv) {
150
  EnclaveContext::GetModule()->RunWorkers(args[0]);
nhynes committed
151 152 153 154 155 156 157 158 159 160 161 162 163
});

TVM_REGISTER_GLOBAL("__sgx_thread_group_join__")
.set_body([](TVMArgs args, TVMRetValue* rv) {
  EnclaveContext::GetModule()->JoinThreads();
});

TVM_REGISTER_GLOBAL("__sgx_set_last_error__")
.set_body([](TVMArgs args, TVMRetValue* rv) {
  std::string err = args[0];
  TVMAPISetLastError(err.c_str());
});

nhynes committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
TVM_REGISTER_GLOBAL("__sgx_println__")
.set_body([](TVMArgs args, TVMRetValue* rv) {
  std::ostringstream msg;
  for (int i = 0; i < args.num_args; ++i) {
    switch (args.type_codes[i]) {
    case kDLInt: msg << static_cast<int64_t>(args[i]); break;
    case kDLUInt: msg << static_cast<uint64_t>(args[i]); break;
    case kDLFloat: msg << static_cast<double>(args[i]); break;
    case kStr:
    case kBytes: {
      std::string val = args[i];
      msg << val;
    }
    break;
    }
    msg << " ";
  }
  LOG(INFO) << msg.str();
});

nhynes committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
extern "C" {

void tvm_ocall_register_export(const char* name, int func_id) {
  EnclaveContext::GetModule()->RegisterExport(name, func_id);
}

void tvm_ocall_packed_func(const char* name,
                           const TVMValue* arg_values,
                           const int* type_codes,
                           int num_args,
                           TVMValue* ret_val,
                           int* ret_type_code) {
  const PackedFunc* f = Registry::Get(name);
  CHECK(f != nullptr) << "ocall to nonexistent function \"" << name << "\"";
  TVMRetValue rv;
  f->CallPacked(TVMArgs(arg_values, type_codes, num_args), &rv);
  rv.MoveToCHost(ret_val, ret_type_code);
}

// Allocates space for return values. The returned pointer is only valid between
// successive calls to `tvm_ocall_reserve_space`.
205 206 207 208 209
TVM_REGISTER_GLOBAL("__sgx_reserve_space__")
.set_body([](TVMArgs args, TVMRetValue* rv) {
  size_t num_bytes = args[0];
  size_t alignment = args[1];

nhynes committed
210 211 212 213 214
  static TVMContext ctx = { kDLCPU, 0 };
  static thread_local void* buf = nullptr;
  static thread_local size_t buf_size = 0;
  static thread_local size_t buf_align = 0;

215
  if (buf_size >= num_bytes && buf_align >= alignment) *rv = nullptr;
nhynes committed
216 217 218 219 220 221

  DeviceAPI::Get(ctx)->FreeDataSpace(ctx, buf);
  buf = DeviceAPI::Get(ctx)->AllocDataSpace(ctx, num_bytes, alignment, {});
  buf_size = num_bytes;
  buf_align = alignment;

222 223
  *rv = buf;
});
nhynes committed
224 225 226 227 228 229 230 231 232 233 234 235 236

}  // extern "C"
}  // namespace sgx

TVM_REGISTER_GLOBAL("module.loadfile_sgx")
.set_body([](TVMArgs args, TVMRetValue* rv) {
  std::shared_ptr<SGXModuleNode> node = std::make_shared<SGXModuleNode>();
  node->Init(args[0]);
  *rv = runtime::Module(node);
});

}  // namespace runtime
}  // namespace tvm