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 "trunks/tpm_simulator_handle.h" 18 19 #include <unistd.h> 20 21 #if defined(USE_SIMULATOR) 22 extern "C" { 23 #include <tpm2/TpmBuildSwitches.h> 24 #include <tpm2/_TPM_Init_fp.h> 25 #include <tpm2/ExecCommand_fp.h> 26 #include <tpm2/Manufacture_fp.h> 27 #include <tpm2/Platform.h> 28 } // extern "C" 29 #endif // USE_SIMULATOR 30 31 #include <base/callback.h> 32 #include <base/logging.h> 33 #include <base/stl_util.h> 34 35 #include "trunks/error_codes.h" 36 37 namespace trunks { 38 39 TpmSimulatorHandle::TpmSimulatorHandle() {} 40 41 TpmSimulatorHandle::~TpmSimulatorHandle() {} 42 43 bool TpmSimulatorHandle::Init() { 44 #if defined(USE_SIMULATOR) 45 // Initialize TPM. 46 CHECK_EQ(chdir("/data/misc/trunksd"), 0); 47 TPM_Manufacture(TRUE); 48 _plat__SetNvAvail(); 49 _plat__Signal_PowerOn(); 50 _TPM_Init(); 51 LOG(INFO) << "Simulator initialized."; 52 #else 53 LOG(FATAL) << "Simulator not configured."; 54 #endif 55 return true; 56 } 57 58 void TpmSimulatorHandle::SendCommand(const std::string& command, 59 const ResponseCallback& callback) { 60 callback.Run(SendCommandAndWait(command)); 61 } 62 63 std::string TpmSimulatorHandle::SendCommandAndWait(const std::string& command) { 64 #if defined(USE_SIMULATOR) 65 unsigned int response_size; 66 unsigned char* response; 67 std::string mutable_command(command); 68 ExecuteCommand(command.size(), reinterpret_cast<unsigned char*>( 69 string_as_array(&mutable_command)), 70 &response_size, &response); 71 return std::string(reinterpret_cast<char*>(response), response_size); 72 #else 73 return CreateErrorResponse(TCTI_RC_GENERAL_FAILURE); 74 #endif 75 } 76 77 } // namespace trunks 78