1 /*
2  * Copyright (C) 2011 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 "signature-inl.h"
18 
19 #include <string.h>
20 
21 #include <ostream>
22 #include <type_traits>
23 
24 #include "base/string_view_cpp20.h"
25 
26 namespace art {
27 
28 using dex::TypeList;
29 
ToString() const30 std::string Signature::ToString() const {
31   if (dex_file_ == nullptr) {
32     CHECK(proto_id_ == nullptr);
33     return "<no signature>";
34   }
35   const TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
36   std::string result;
37   if (params == nullptr) {
38     result += "()";
39   } else {
40     result += "(";
41     for (uint32_t i = 0; i < params->Size(); ++i) {
42       result += dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_);
43     }
44     result += ")";
45   }
46   result += dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
47   return result;
48 }
49 
GetNumberOfParameters() const50 uint32_t Signature::GetNumberOfParameters() const {
51   const TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
52   return (params != nullptr) ? params->Size() : 0;
53 }
54 
IsVoid() const55 bool Signature::IsVoid() const {
56   const char* return_type = dex_file_->GetReturnTypeDescriptor(*proto_id_);
57   return strcmp(return_type, "V") == 0;
58 }
59 
operator ==(std::string_view rhs) const60 bool Signature::operator==(std::string_view rhs) const {
61   if (dex_file_ == nullptr) {
62     return false;
63   }
64   std::string_view tail(rhs);
65   if (!StartsWith(tail, "(")) {
66     return false;  // Invalid signature
67   }
68   tail.remove_prefix(1);  // "(";
69   const TypeList* params = dex_file_->GetProtoParameters(*proto_id_);
70   if (params != nullptr) {
71     for (uint32_t i = 0; i < params->Size(); ++i) {
72       std::string_view param(dex_file_->StringByTypeIdx(params->GetTypeItem(i).type_idx_));
73       if (!StartsWith(tail, param)) {
74         return false;
75       }
76       tail.remove_prefix(param.length());
77     }
78   }
79   if (!StartsWith(tail, ")")) {
80     return false;
81   }
82   tail.remove_prefix(1);  // ")";
83   return tail == dex_file_->StringByTypeIdx(proto_id_->return_type_idx_);
84 }
85 
operator <<(std::ostream & os,const Signature & sig)86 std::ostream& operator<<(std::ostream& os, const Signature& sig) {
87   return os << sig.ToString();
88 }
89 
90 }  // namespace art
91