1 /* 2 * Copyright (C) 2015 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 #if defined(__ANDROID__) 18 #include <android-base/properties.h> 19 #endif 20 21 #include "command.h" 22 #include "environment.h" 23 24 #if defined(__ANDROID__) 25 26 bool AndroidSecurityCheck() { 27 // Simpleperf can be executed by the shell, or by apps themselves. To avoid malicious apps 28 // exploiting perf_event_open interface via simpleperf, simpleperf needs proof that the user 29 // is expecting simpleperf to be ran: 30 // 1) On Android < R, perf_event_open is secured by perf_event_paranoid, which is controlled 31 // by security.perf_harden property. perf_event_open syscall can be used only after user setting 32 // security.perf_harden to 0 in shell. So we don't need to check security.perf_harden explicitly. 33 // 2) On Android R, perf_event_open may be controlled by selinux instead of 34 // perf_event_paranoid. So we need to check security.perf_harden explicitly. If simpleperf is 35 // running via shell, we already know the origin of the request is the user, so set the property 36 // ourselves for convenience. When started by the app, we won't have the permission to set the 37 // property, so the user will need to prove this intent by setting it manually via shell. 38 if (GetAndroidVersion() >= 11) { 39 std::string prop_name = "security.perf_harden"; 40 if (android::base::GetProperty(prop_name, "") != "0") { 41 if (!android::base::SetProperty(prop_name, "0")) { 42 fprintf(stderr, 43 "failed to set system property security.perf_harden to 0.\n" 44 "Try using `adb shell setprop security.perf_harden 0` to allow profiling.\n"); 45 return false; 46 } 47 } 48 } 49 return true; 50 } 51 52 #endif 53 54 int main(int argc, char** argv) { 55 #if defined(__ANDROID__) 56 if (!AndroidSecurityCheck()) { 57 return 1; 58 } 59 #endif 60 return RunSimpleperfCmd(argc, argv) ? 0 : 1; 61 } 62