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 package com.android.permissioncontroller.permission.utils 18 19 import java.util.Collections.reverse 20 21 /** 22 * A short version of the permission-only stack trace, suitable to use in debug logs. 23 * 24 * See [toShortString] 25 */ shortStackTracenull26fun shortStackTrace() = permissionsStackTrace().toShortString() 27 28 /** [StackTraceElement]s of only the permission-related frames */ 29 fun permissionsStackTrace() = 30 stackTraceWithin("com.android.permissioncontroller").dropLastWhile { 31 it.className.contains(".DebugUtils") 32 } 33 34 /** 35 * [StackTraceElement]s of only frames who's [full class name][StackTraceElement.getClassName] 36 * starts with [pkgPrefix] 37 */ stackTraceWithinnull38fun stackTraceWithin(pkgPrefix: String) = 39 Thread.currentThread() 40 .stackTrace 41 .dropWhile { !it.className.startsWith(pkgPrefix) } <lambda>null42 .takeWhile { it.className.startsWith(pkgPrefix) } 43 44 /** 45 * Renders a stack trace slice to a short-ish single-line string. 46 * 47 * Suitable for debugging when full stack trace can be too spammy. 48 */ toShortStringnull49fun List<StackTraceElement>.toShortString(): String { 50 reverse(this) 51 return joinToString(" -> ") { 52 val fullSimpleClassName = it.className.substringAfterLast(".") 53 var simpleClassName = fullSimpleClassName.substringAfterLast("\$") 54 if (simpleClassName.isNotEmpty() && simpleClassName[0].isDigit()) { 55 simpleClassName = fullSimpleClassName 56 } 57 "$simpleClassName.${it.methodName}:${it.lineNumber}" 58 } 59 } 60