/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Slog;
import java.io.FileDescriptor;
import java.io.PrintWriter;
/**
* LockGuard is a mechanism to help detect lock inversions inside the system
* server. It works by requiring each lock acquisition site to follow this
* pattern:
*
*
*
* The {@link #guard(Object)} method internally verifies that all locking is
* done in a consistent order, and will log if any inversion is detected. For
* example, if the calling thread is trying to acquire the
* {@code ActivityManager} lock while holding the {@code PackageManager} lock,
* it will yell.
*
* This class requires no prior knowledge of locks or their ordering; it derives
* all of this data at runtime. However, this means the overhead is
* substantial and it should not be enabled by default. For example,
* here are some benchmarked timings:
*
*
An unguarded synchronized block takes 40ns.
*
A guarded synchronized block takes 50ns when disabled.
*
A guarded synchronized block takes 460ns per lock checked when enabled.
*
*
* This class also supports a second simpler mode of operation where well-known
* locks are explicitly registered and checked via indexes.
*/
public class LockGuard {
private static final String TAG = "LockGuard";
public static final boolean ENABLED = false;
/**
* Well-known locks ordered by fixed index. Locks with a specific index
* should never be acquired while holding a lock of a lower index.
*/
public static final int INDEX_APP_OPS = 0;
public static final int INDEX_POWER = 1;
public static final int INDEX_USER = 2;
public static final int INDEX_PACKAGES = 3;
public static final int INDEX_STORAGE = 4;
public static final int INDEX_WINDOW = 5;
public static final int INDEX_ACTIVITY = 6;
private static Object[] sKnownFixed = new Object[INDEX_ACTIVITY + 1];
private static ArrayMap