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 
17 #include "compat_framework.h"
18 
19 #include <sys/types.h>
20 #include <unistd.h>
21 
22 #include "android-base/logging.h"
23 #include "thread-current-inl.h"
24 
25 namespace art {
26 
27 // Compat change states as strings.
28 static constexpr char kUnknownChangeState[] = "UNKNOWN";
29 static constexpr char kEnabledChangeState[] = "ENABLED";
30 static constexpr char kDisabledChangeState[] = "DISABLED";
31 static constexpr char kLoggedState[] = "LOGGED";
32 
CompatFramework()33 CompatFramework::CompatFramework()
34     : reported_compat_changes_lock_("reported compat changes lock") {}
35 
~CompatFramework()36 CompatFramework::~CompatFramework() {}
37 
IsChangeEnabled(uint64_t change_id)38 bool CompatFramework::IsChangeEnabled(uint64_t change_id) {
39   const auto enabled = disabled_compat_changes_.count(change_id) == 0;
40   ReportChange(change_id, enabled ? ChangeState::kEnabled : ChangeState::kDisabled);
41   return enabled;
42 }
43 
LogChange(uint64_t change_id)44 void CompatFramework::LogChange(uint64_t change_id) {
45   ReportChange(change_id, ChangeState::kLogged);
46 }
47 
ReportChange(uint64_t change_id,ChangeState state)48 void CompatFramework::ReportChange(uint64_t change_id, ChangeState state) {
49   MutexLock mu(Thread::Current(), reported_compat_changes_lock_);
50   bool already_reported = reported_compat_changes_.count(change_id) != 0;
51   if (already_reported) {
52     return;
53   }
54   LOG(DEBUG) << "Compat change id reported: " << change_id << "; UID " << getuid()
55             << "; state: " << ChangeStateToString(state);
56   // TODO(145743810): add an up call to java to log to statsd
57   reported_compat_changes_.emplace(change_id);
58 }
59 
ChangeStateToString(ChangeState state)60 std::string_view CompatFramework::ChangeStateToString(ChangeState state) {
61   switch (state) {
62     case ChangeState::kUnknown:
63       return kUnknownChangeState;
64     case ChangeState::kEnabled:
65       return kEnabledChangeState;
66     case ChangeState::kDisabled:
67       return kDisabledChangeState;
68     case ChangeState::kLogged:
69       return kLoggedState;
70   }
71 }
72 
73 }  // namespace art
74