1 //
2 // Copyright (C) 2020 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 #include "tpm_resource_manager.h"
17 
18 #include <android-base/logging.h>
19 #include <tss2/tss2_rc.h>
20 
ObjectSlot(TpmResourceManager * resource_manager)21 TpmResourceManager::ObjectSlot::ObjectSlot(TpmResourceManager* resource_manager)
22     : ObjectSlot(resource_manager, ESYS_TR_NONE) {
23 }
24 
ObjectSlot(TpmResourceManager * resource_manager,ESYS_TR resource)25 TpmResourceManager::ObjectSlot::ObjectSlot(TpmResourceManager* resource_manager,
26                                            ESYS_TR resource)
27     : resource_manager_(resource_manager), resource_(resource) {
28   LOG(VERBOSE) << "Resource allocated";
29 }
30 
~ObjectSlot()31 TpmResourceManager::ObjectSlot::~ObjectSlot() {
32   if (resource_ != ESYS_TR_NONE) {
33     LOG(VERBOSE) << "Freeing resource";
34     auto rc = Esys_FlushContext(resource_manager_->esys_, resource_);
35     if (rc != TPM2_RC_SUCCESS) {
36       LOG(ERROR) << "Esys_FlushContext failed: " << Tss2_RC_Decode(rc)
37                 << "(" << rc << ")";
38     }
39   } else {
40     LOG(VERBOSE) << "Resource is NONE";
41   }
42   resource_manager_->used_slots_--;
43 }
44 
get()45 ESYS_TR TpmResourceManager::ObjectSlot::get() {
46   return resource_;
47 }
48 
set(ESYS_TR resource)49 void TpmResourceManager::ObjectSlot::set(ESYS_TR resource) {
50   resource_ = resource;
51 }
52 
TpmResourceManager(ESYS_CONTEXT * esys)53 TpmResourceManager::TpmResourceManager(ESYS_CONTEXT* esys)
54     : esys_(esys), maximum_object_slots_(3), used_slots_(0) {
55   // TODO(b/158791154): Find maximum_object_slots dynamically using
56   // TPM2_GetCapability. Now equal to MAX_LOADED_OBJECTS from TpmProfile.h.
57 }
58 
~TpmResourceManager()59 TpmResourceManager::~TpmResourceManager() {
60   if (used_slots_ > 0) {
61     LOG(FATAL) << "Outstanding TpmResourceManager::ObjectSlot instances. "
62                   "These hold a dangling pointer to this instance.";
63   }
64 }
65 
Esys()66 ESYS_CONTEXT* TpmResourceManager::Esys() {
67   return esys_;
68 }
69 
ReserveSlot()70 TpmObjectSlot TpmResourceManager::ReserveSlot() {
71   auto slot_num = used_slots_.fetch_add(1);
72   if (slot_num >= maximum_object_slots_) {
73       used_slots_--;
74       return nullptr;
75   }
76   return TpmObjectSlot{new ObjectSlot(this)};
77 }
78