1 /*
2  * Copyright (C) 2016 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 #ifndef ART_COMPILER_UTILS_ATOMIC_DEX_REF_MAP_H_
18 #define ART_COMPILER_UTILS_ATOMIC_DEX_REF_MAP_H_
19 
20 #include "base/atomic.h"
21 #include "base/dchecked_vector.h"
22 #include "base/safe_map.h"
23 #include "dex/dex_file_reference.h"
24 
25 namespace art {
26 
27 class DexFile;
28 
29 // Used by CompilerCallbacks to track verification information from the Runtime.
30 template <typename DexFileReferenceType, typename Value>
31 class AtomicDexRefMap {
32  public:
AtomicDexRefMap()33   AtomicDexRefMap() {}
~AtomicDexRefMap()34   ~AtomicDexRefMap() {}
35 
36   // Atomically swap the element in if the existing value matches expected.
37   enum InsertResult {
38     kInsertResultInvalidDexFile,
39     kInsertResultCASFailure,
40     kInsertResultSuccess,
41   };
42   InsertResult Insert(const DexFileReferenceType& ref,
43                       const Value& expected,
44                       const Value& desired);
45 
46   // Retreive an item, returns false if the dex file is not added.
47   bool Get(const DexFileReferenceType& ref, Value* out) const;
48 
49   // Remove an item and return the existing value. Returns false if the dex file is not added.
50   bool Remove(const DexFileReferenceType& ref, Value* out);
51 
52   // Dex files must be added before method references belonging to them can be used as keys. Not
53   // thread safe.
54   void AddDexFile(const DexFile* dex_file);
55   void AddDexFiles(const std::vector<const DexFile*>& dex_files);
56 
HaveDexFile(const DexFile * dex_file)57   bool HaveDexFile(const DexFile* dex_file) const {
58     return arrays_.find(dex_file) != arrays_.end();
59   }
60 
61   // Visit all of the dex files and elements.
62   template <typename Visitor>
63   void Visit(const Visitor& visitor);
64 
65   void ClearEntries();
66 
67  private:
68   // Verified methods. The method array is fixed to avoid needing a lock to extend it.
69   using ElementArray = dchecked_vector<Atomic<Value>>;
70   using DexFileArrays = SafeMap<const DexFile*, ElementArray>;
71 
72   const ElementArray* GetArray(const DexFile* dex_file) const;
73   ElementArray* GetArray(const DexFile* dex_file);
74 
75   static size_t NumberOfDexIndices(const DexFile* dex_file);
76 
77   DexFileArrays arrays_;
78 };
79 
80 }  // namespace art
81 
82 #endif  // ART_COMPILER_UTILS_ATOMIC_DEX_REF_MAP_H_
83