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  */
shortStackTracenull26 fun shortStackTrace() = permissionsStackTrace().toShortString()
27 
28 /**
29  * [StackTraceElement]s of only the permission-related frames
30  */
31 fun permissionsStackTrace() = stackTraceWithin("com.android.permissioncontroller")
32     .dropLastWhile { it.className.contains(".DebugUtils") }
33 
34 /**
35  * [StackTraceElement]s of only frames who's [full class name][StackTraceElement.getClassName]
36  * starts with [pkgPrefix]
37  */
stackTraceWithinnull38 fun stackTraceWithin(pkgPrefix: String) = Thread
39     .currentThread()
40     .stackTrace
41     .dropWhile {
42         !it.className.startsWith(pkgPrefix)
43     }.takeWhile {
44         it.className.startsWith(pkgPrefix)
45     }
46 
47 /**
48  * Renders a stack trace slice to a short-ish single-line string.
49  *
50  * Suitable for debugging when full stack trace can be too spammy.
51  */
toShortStringnull52 fun List<StackTraceElement>.toShortString(): String {
53     reverse(this)
54     return joinToString(" -> ") {
55         val fullSimpleClassName = it.className.substringAfterLast(".")
56         var simpleClassName = fullSimpleClassName.substringAfterLast("\$")
57         if (simpleClassName.isNotEmpty() && simpleClassName[0].isDigit()) {
58             simpleClassName = fullSimpleClassName
59         }
60         "$simpleClassName.${it.methodName}:${it.lineNumber}"
61     }
62 }
63