Initial import of ADIF API reverse-engineering toolkit

This commit is contained in:
2025-12-16 08:37:56 +01:00
commit 60388529c1
11486 changed files with 1086536 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
package com.google.firebase.crashlytics.internal.common;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.google.firebase.crashlytics.internal.DevelopmentPlatformProvider;
import java.util.List;
/* loaded from: classes3.dex */
public class AppData {
public final String buildId;
public final List<BuildIdInfo> buildIdInfoList;
public final DevelopmentPlatformProvider developmentPlatformProvider;
public final String googleAppId;
public final String installerPackageName;
public final String packageName;
public final String versionCode;
public final String versionName;
public AppData(String str, String str2, List<BuildIdInfo> list, String str3, String str4, String str5, String str6, DevelopmentPlatformProvider developmentPlatformProvider) {
this.googleAppId = str;
this.buildId = str2;
this.buildIdInfoList = list;
this.installerPackageName = str3;
this.packageName = str4;
this.versionCode = str5;
this.versionName = str6;
this.developmentPlatformProvider = developmentPlatformProvider;
}
public static AppData create(Context context, IdManager idManager, String str, String str2, List<BuildIdInfo> list, DevelopmentPlatformProvider developmentPlatformProvider) throws PackageManager.NameNotFoundException {
String packageName = context.getPackageName();
String installerPackageName = idManager.getInstallerPackageName();
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
String appBuildVersion = getAppBuildVersion(packageInfo);
String str3 = packageInfo.versionName;
if (str3 == null) {
str3 = IdManager.DEFAULT_VERSION_NAME;
}
return new AppData(str, str2, list, installerPackageName, packageName, appBuildVersion, str3, developmentPlatformProvider);
}
private static String getAppBuildVersion(PackageInfo packageInfo) {
return Long.toString(packageInfo.getLongVersionCode());
}
}

View File

@@ -0,0 +1,63 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import java.io.File;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public final class AutoValue_CrashlyticsReportWithSessionId extends CrashlyticsReportWithSessionId {
private final CrashlyticsReport report;
private final File reportFile;
private final String sessionId;
public AutoValue_CrashlyticsReportWithSessionId(CrashlyticsReport crashlyticsReport, String str, File file) {
if (crashlyticsReport == null) {
throw new NullPointerException("Null report");
}
this.report = crashlyticsReport;
if (str == null) {
throw new NullPointerException("Null sessionId");
}
this.sessionId = str;
if (file == null) {
throw new NullPointerException("Null reportFile");
}
this.reportFile = file;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof CrashlyticsReportWithSessionId) {
CrashlyticsReportWithSessionId crashlyticsReportWithSessionId = (CrashlyticsReportWithSessionId) obj;
if (this.report.equals(crashlyticsReportWithSessionId.getReport()) && this.sessionId.equals(crashlyticsReportWithSessionId.getSessionId()) && this.reportFile.equals(crashlyticsReportWithSessionId.getReportFile())) {
return true;
}
}
return false;
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsReportWithSessionId
public CrashlyticsReport getReport() {
return this.report;
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsReportWithSessionId
public File getReportFile() {
return this.reportFile;
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsReportWithSessionId
public String getSessionId() {
return this.sessionId;
}
public int hashCode() {
return this.reportFile.hashCode() ^ ((((this.report.hashCode() ^ 1000003) * 1000003) ^ this.sessionId.hashCode()) * 1000003);
}
public String toString() {
return "CrashlyticsReportWithSessionId{report=" + this.report + ", sessionId=" + this.sessionId + ", reportFile=" + this.reportFile + "}";
}
}

View File

@@ -0,0 +1,55 @@
package com.google.firebase.crashlytics.internal.common;
import C.w;
import com.google.firebase.crashlytics.internal.common.InstallIdProvider;
/* loaded from: classes3.dex */
final class AutoValue_InstallIdProvider_InstallIds extends InstallIdProvider.InstallIds {
private final String crashlyticsInstallId;
private final String firebaseInstallationId;
public AutoValue_InstallIdProvider_InstallIds(String str, String str2) {
if (str == null) {
throw new NullPointerException("Null crashlyticsInstallId");
}
this.crashlyticsInstallId = str;
this.firebaseInstallationId = str2;
}
public boolean equals(Object obj) {
String str;
if (obj == this) {
return true;
}
if (obj instanceof InstallIdProvider.InstallIds) {
InstallIdProvider.InstallIds installIds = (InstallIdProvider.InstallIds) obj;
if (this.crashlyticsInstallId.equals(installIds.getCrashlyticsInstallId()) && ((str = this.firebaseInstallationId) != null ? str.equals(installIds.getFirebaseInstallationId()) : installIds.getFirebaseInstallationId() == null)) {
return true;
}
}
return false;
}
@Override // com.google.firebase.crashlytics.internal.common.InstallIdProvider.InstallIds
public String getCrashlyticsInstallId() {
return this.crashlyticsInstallId;
}
@Override // com.google.firebase.crashlytics.internal.common.InstallIdProvider.InstallIds
public String getFirebaseInstallationId() {
return this.firebaseInstallationId;
}
public int hashCode() {
int hashCode = (this.crashlyticsInstallId.hashCode() ^ 1000003) * 1000003;
String str = this.firebaseInstallationId;
return (str == null ? 0 : str.hashCode()) ^ hashCode;
}
public String toString() {
StringBuilder sb = new StringBuilder("InstallIds{crashlyticsInstallId=");
sb.append(this.crashlyticsInstallId);
sb.append(", firebaseInstallationId=");
return w.r(sb, this.firebaseInstallationId, "}");
}
}

View File

@@ -0,0 +1,14 @@
package com.google.firebase.crashlytics.internal.common;
import android.os.Process;
/* loaded from: classes3.dex */
public abstract class BackgroundPriorityRunnable implements Runnable {
public abstract void onRun();
@Override // java.lang.Runnable
public final void run() {
Process.setThreadPriority(10);
onRun();
}
}

View File

@@ -0,0 +1,69 @@
package com.google.firebase.crashlytics.internal.common;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crashlytics.internal.Logger;
/* loaded from: classes3.dex */
class BatteryState {
static final int VELOCITY_CHARGING = 2;
static final int VELOCITY_FULL = 3;
static final int VELOCITY_UNPLUGGED = 1;
private final Float level;
private final boolean powerConnected;
private BatteryState(Float f2, boolean z3) {
this.powerConnected = z3;
this.level = f2;
}
public static BatteryState get(Context context) {
boolean z3 = false;
Float f2 = null;
try {
Intent registerReceiver = context.registerReceiver(null, new IntentFilter("android.intent.action.BATTERY_CHANGED"));
if (registerReceiver != null) {
z3 = isPowerConnected(registerReceiver);
f2 = getLevel(registerReceiver);
}
} catch (IllegalStateException e4) {
Logger.getLogger().e("An error occurred getting battery state.", e4);
}
return new BatteryState(f2, z3);
}
private static Float getLevel(Intent intent) {
int intExtra = intent.getIntExtra(FirebaseAnalytics.Param.LEVEL, -1);
int intExtra2 = intent.getIntExtra("scale", -1);
if (intExtra == -1 || intExtra2 == -1) {
return null;
}
return Float.valueOf(intExtra / intExtra2);
}
public Float getBatteryLevel() {
return this.level;
}
public int getBatteryVelocity() {
Float f2;
if (!this.powerConnected || (f2 = this.level) == null) {
return 1;
}
return ((double) f2.floatValue()) < 0.99d ? 2 : 3;
}
public boolean isPowerConnected() {
return this.powerConnected;
}
private static boolean isPowerConnected(Intent intent) {
int intExtra = intent.getIntExtra("status", -1);
if (intExtra == -1) {
return false;
}
return intExtra == 2 || intExtra == 5;
}
}

View File

@@ -0,0 +1,26 @@
package com.google.firebase.crashlytics.internal.common;
/* loaded from: classes3.dex */
public class BuildIdInfo {
private final String arch;
private final String buildId;
private final String libraryName;
public BuildIdInfo(String str, String str2, String str3) {
this.libraryName = str;
this.arch = str2;
this.buildId = str3;
}
public String getArch() {
return this.arch;
}
public String getBuildId() {
return this.buildId;
}
public String getLibraryName() {
return this.libraryName;
}
}

View File

@@ -0,0 +1,79 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPOutputStream;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public class BytesBackedNativeSessionFile implements NativeSessionFile {
private final byte[] bytes;
private final String dataTransportFilename;
private final String reportsEndpointFilename;
public BytesBackedNativeSessionFile(String str, String str2, byte[] bArr) {
this.dataTransportFilename = str;
this.reportsEndpointFilename = str2;
this.bytes = bArr;
}
private byte[] asGzippedBytes() {
if (isEmpty()) {
return null;
}
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
try {
gZIPOutputStream.write(this.bytes);
gZIPOutputStream.finish();
byte[] byteArray = byteArrayOutputStream.toByteArray();
gZIPOutputStream.close();
byteArrayOutputStream.close();
return byteArray;
} finally {
}
} catch (Throwable th) {
try {
byteArrayOutputStream.close();
} catch (Throwable th2) {
th.addSuppressed(th2);
}
throw th;
}
} catch (IOException unused) {
return null;
}
}
private boolean isEmpty() {
byte[] bArr = this.bytes;
return bArr == null || bArr.length == 0;
}
@Override // com.google.firebase.crashlytics.internal.common.NativeSessionFile
public CrashlyticsReport.FilesPayload.File asFilePayload() {
byte[] asGzippedBytes = asGzippedBytes();
if (asGzippedBytes == null) {
return null;
}
return CrashlyticsReport.FilesPayload.File.builder().setContents(asGzippedBytes).setFilename(this.dataTransportFilename).build();
}
@Override // com.google.firebase.crashlytics.internal.common.NativeSessionFile
public String getReportsEndpointFilename() {
return this.reportsEndpointFilename;
}
@Override // com.google.firebase.crashlytics.internal.common.NativeSessionFile
public InputStream getStream() {
if (isEmpty()) {
return null;
}
return new ByteArrayInputStream(this.bytes);
}
}

View File

@@ -0,0 +1,70 @@
package com.google.firebase.crashlytics.internal.common;
import android.os.Process;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicLong;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public class CLSUUID {
private static String _clsId;
private static final AtomicLong _sequenceNumber = new AtomicLong(0);
public CLSUUID(IdManager idManager) {
byte[] bArr = new byte[10];
populateTime(bArr);
populateSequenceNumber(bArr);
populatePID(bArr);
String sha1 = CommonUtils.sha1(idManager.getInstallIds().getCrashlyticsInstallId());
String hexify = CommonUtils.hexify(bArr);
Locale locale = Locale.US;
_clsId = String.format(locale, "%s%s%s%s", hexify.substring(0, 12), hexify.substring(12, 16), hexify.subSequence(16, 20), sha1.substring(0, 12)).toUpperCase(locale);
}
private static byte[] convertLongToFourByteBuffer(long j4) {
ByteBuffer allocate = ByteBuffer.allocate(4);
allocate.putInt((int) j4);
allocate.order(ByteOrder.BIG_ENDIAN);
allocate.position(0);
return allocate.array();
}
private static byte[] convertLongToTwoByteBuffer(long j4) {
ByteBuffer allocate = ByteBuffer.allocate(2);
allocate.putShort((short) j4);
allocate.order(ByteOrder.BIG_ENDIAN);
allocate.position(0);
return allocate.array();
}
private void populatePID(byte[] bArr) {
byte[] convertLongToTwoByteBuffer = convertLongToTwoByteBuffer(Integer.valueOf(Process.myPid()).shortValue());
bArr[8] = convertLongToTwoByteBuffer[0];
bArr[9] = convertLongToTwoByteBuffer[1];
}
private void populateSequenceNumber(byte[] bArr) {
byte[] convertLongToTwoByteBuffer = convertLongToTwoByteBuffer(_sequenceNumber.incrementAndGet());
bArr[6] = convertLongToTwoByteBuffer[0];
bArr[7] = convertLongToTwoByteBuffer[1];
}
private void populateTime(byte[] bArr) {
long time = new Date().getTime();
byte[] convertLongToFourByteBuffer = convertLongToFourByteBuffer(time / 1000);
bArr[0] = convertLongToFourByteBuffer[0];
bArr[1] = convertLongToFourByteBuffer[1];
bArr[2] = convertLongToFourByteBuffer[2];
bArr[3] = convertLongToFourByteBuffer[3];
byte[] convertLongToTwoByteBuffer = convertLongToTwoByteBuffer(time % 1000);
bArr[4] = convertLongToTwoByteBuffer[0];
bArr[5] = convertLongToTwoByteBuffer[1];
}
public String toString() {
return _clsId;
}
}

View File

@@ -0,0 +1,340 @@
package com.google.firebase.crashlytics.internal.common;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Debug;
import android.os.StatFs;
import android.text.TextUtils;
import com.google.firebase.crashlytics.internal.Logger;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import kotlin.UByte;
/* loaded from: classes3.dex */
public class CommonUtils {
static final String BUILD_IDS_ARCH_RESOURCE_NAME = "com.google.firebase.crashlytics.build_ids_arch";
static final String BUILD_IDS_BUILD_ID_RESOURCE_NAME = "com.google.firebase.crashlytics.build_ids_build_id";
static final String BUILD_IDS_LIB_NAMES_RESOURCE_NAME = "com.google.firebase.crashlytics.build_ids_lib";
public static final int DEVICE_STATE_BETAOS = 8;
public static final int DEVICE_STATE_COMPROMISEDLIBRARIES = 32;
public static final int DEVICE_STATE_DEBUGGERATTACHED = 4;
public static final int DEVICE_STATE_ISSIMULATOR = 1;
public static final int DEVICE_STATE_JAILBROKEN = 2;
public static final int DEVICE_STATE_VENDORINTERNAL = 16;
private static final String GOLDFISH = "goldfish";
private static final char[] HEX_VALUES = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
static final String LEGACY_MAPPING_FILE_ID_RESOURCE_NAME = "com.crashlytics.android.build_id";
public static final String LEGACY_SHARED_PREFS_NAME = "com.crashlytics.prefs";
static final String MAPPING_FILE_ID_RESOURCE_NAME = "com.google.firebase.crashlytics.mapping_file_id";
private static final String RANCHU = "ranchu";
private static final String SDK = "sdk";
private static final String SHA1_INSTANCE = "SHA-1";
public static final String SHARED_PREFS_NAME = "com.google.firebase.crashlytics";
/* loaded from: classes3.dex */
public enum Architecture {
X86_32,
X86_64,
ARM_UNKNOWN,
PPC,
PPC64,
ARMV6,
ARMV7,
UNKNOWN,
ARMV7S,
ARM64;
private static final Map<String, Architecture> matcher;
static {
Architecture architecture = X86_32;
Architecture architecture2 = ARMV6;
Architecture architecture3 = ARMV7;
Architecture architecture4 = ARM64;
HashMap hashMap = new HashMap(4);
matcher = hashMap;
hashMap.put("armeabi-v7a", architecture3);
hashMap.put("armeabi", architecture2);
hashMap.put("arm64-v8a", architecture4);
hashMap.put("x86", architecture);
}
public static Architecture getValue() {
String str = Build.CPU_ABI;
if (TextUtils.isEmpty(str)) {
Logger.getLogger().v("Architecture#getValue()::Build.CPU_ABI returned null or empty");
return UNKNOWN;
}
Architecture architecture = matcher.get(str.toLowerCase(Locale.US));
return architecture == null ? UNKNOWN : architecture;
}
}
public static long calculateFreeRamInBytes(Context context) {
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
((ActivityManager) context.getSystemService("activity")).getMemoryInfo(memoryInfo);
return memoryInfo.availMem;
}
public static synchronized long calculateTotalRamInBytes(Context context) {
long j4;
synchronized (CommonUtils.class) {
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
((ActivityManager) context.getSystemService("activity")).getMemoryInfo(memoryInfo);
j4 = memoryInfo.totalMem;
}
return j4;
}
public static long calculateUsedDiskSpaceInBytes(String str) {
long blockSize = new StatFs(str).getBlockSize();
return (r0.getBlockCount() * blockSize) - (blockSize * r0.getAvailableBlocks());
}
@SuppressLint({"MissingPermission"})
public static boolean canTryConnection(Context context) {
if (!checkPermission(context, "android.permission.ACCESS_NETWORK_STATE")) {
return true;
}
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
public static boolean checkPermission(Context context, String str) {
return context.checkCallingOrSelfPermission(str) == 0;
}
public static void closeOrLog(Closeable closeable, String str) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e4) {
Logger.getLogger().e(str, e4);
}
}
}
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException e4) {
throw e4;
} catch (Exception unused) {
}
}
}
public static String createInstanceIdFrom(String... strArr) {
if (strArr != null && strArr.length != 0) {
ArrayList arrayList = new ArrayList();
for (String str : strArr) {
if (str != null) {
arrayList.add(str.replace("-", "").toLowerCase(Locale.US));
}
}
Collections.sort(arrayList);
StringBuilder sb = new StringBuilder();
Iterator it = arrayList.iterator();
while (it.hasNext()) {
sb.append((String) it.next());
}
String sb2 = sb.toString();
if (sb2.length() > 0) {
return sha1(sb2);
}
}
return null;
}
public static boolean getBooleanResourceValue(Context context, String str, boolean z3) {
Resources resources;
if (context != null && (resources = context.getResources()) != null) {
int resourcesIdentifier = getResourcesIdentifier(context, str, "bool");
if (resourcesIdentifier > 0) {
return resources.getBoolean(resourcesIdentifier);
}
int resourcesIdentifier2 = getResourcesIdentifier(context, str, "string");
if (resourcesIdentifier2 > 0) {
return Boolean.parseBoolean(context.getString(resourcesIdentifier2));
}
}
return z3;
}
public static List<BuildIdInfo> getBuildIdInfo(Context context) {
ArrayList arrayList = new ArrayList();
int resourcesIdentifier = getResourcesIdentifier(context, BUILD_IDS_LIB_NAMES_RESOURCE_NAME, "array");
int resourcesIdentifier2 = getResourcesIdentifier(context, BUILD_IDS_ARCH_RESOURCE_NAME, "array");
int resourcesIdentifier3 = getResourcesIdentifier(context, BUILD_IDS_BUILD_ID_RESOURCE_NAME, "array");
if (resourcesIdentifier == 0 || resourcesIdentifier2 == 0 || resourcesIdentifier3 == 0) {
Logger.getLogger().d(String.format("Could not find resources: %d %d %d", Integer.valueOf(resourcesIdentifier), Integer.valueOf(resourcesIdentifier2), Integer.valueOf(resourcesIdentifier3)));
return arrayList;
}
String[] stringArray = context.getResources().getStringArray(resourcesIdentifier);
String[] stringArray2 = context.getResources().getStringArray(resourcesIdentifier2);
String[] stringArray3 = context.getResources().getStringArray(resourcesIdentifier3);
if (stringArray.length != stringArray3.length || stringArray2.length != stringArray3.length) {
Logger.getLogger().d(String.format("Lengths did not match: %d %d %d", Integer.valueOf(stringArray.length), Integer.valueOf(stringArray2.length), Integer.valueOf(stringArray3.length)));
return arrayList;
}
for (int i = 0; i < stringArray3.length; i++) {
arrayList.add(new BuildIdInfo(stringArray[i], stringArray2[i], stringArray3[i]));
}
return arrayList;
}
public static int getCpuArchitectureInt() {
return Architecture.getValue().ordinal();
}
/* JADX WARN: Multi-variable type inference failed */
/* JADX WARN: Type inference failed for: r0v1, types: [int] */
/* JADX WARN: Type inference failed for: r0v5 */
/* JADX WARN: Type inference failed for: r0v6 */
public static int getDeviceState() {
boolean isEmulator = isEmulator();
?? r02 = isEmulator;
if (isRooted()) {
r02 = (isEmulator ? 1 : 0) | 2;
}
return isDebuggerAttached() ? r02 | 4 : r02;
}
public static SharedPreferences getLegacySharedPrefs(Context context) {
return context.getSharedPreferences(LEGACY_SHARED_PREFS_NAME, 0);
}
public static String getMappingFileId(Context context) {
int resourcesIdentifier = getResourcesIdentifier(context, MAPPING_FILE_ID_RESOURCE_NAME, "string");
if (resourcesIdentifier == 0) {
resourcesIdentifier = getResourcesIdentifier(context, LEGACY_MAPPING_FILE_ID_RESOURCE_NAME, "string");
}
if (resourcesIdentifier != 0) {
return context.getResources().getString(resourcesIdentifier);
}
return null;
}
public static boolean getProximitySensorEnabled(Context context) {
return (isEmulator() || ((SensorManager) context.getSystemService("sensor")).getDefaultSensor(8) == null) ? false : true;
}
public static String getResourcePackageName(Context context) {
int i = context.getApplicationContext().getApplicationInfo().icon;
if (i <= 0) {
return context.getPackageName();
}
try {
String resourcePackageName = context.getResources().getResourcePackageName(i);
return "android".equals(resourcePackageName) ? context.getPackageName() : resourcePackageName;
} catch (Resources.NotFoundException unused) {
return context.getPackageName();
}
}
public static int getResourcesIdentifier(Context context, String str, String str2) {
return context.getResources().getIdentifier(str, str2, getResourcePackageName(context));
}
public static SharedPreferences getSharedPrefs(Context context) {
return context.getSharedPreferences("com.google.firebase.crashlytics", 0);
}
private static String hash(String str, String str2) {
return hash(str.getBytes(), str2);
}
public static String hexify(byte[] bArr) {
char[] cArr = new char[bArr.length * 2];
for (int i = 0; i < bArr.length; i++) {
byte b4 = bArr[i];
int i4 = b4 & UByte.MAX_VALUE;
int i5 = i * 2;
char[] cArr2 = HEX_VALUES;
cArr[i5] = cArr2[i4 >>> 4];
cArr[i5 + 1] = cArr2[b4 & 15];
}
return new String(cArr);
}
public static boolean isAppDebuggable(Context context) {
return (context.getApplicationInfo().flags & 2) != 0;
}
public static boolean isDebuggerAttached() {
return Debug.isDebuggerConnected() || Debug.waitingForDebugger();
}
public static boolean isEmulator() {
if (Build.PRODUCT.contains(SDK)) {
return true;
}
String str = Build.HARDWARE;
return str.contains(GOLDFISH) || str.contains(RANCHU);
}
@Deprecated
public static boolean isLoggingEnabled(Context context) {
return false;
}
public static boolean isRooted() {
boolean isEmulator = isEmulator();
String str = Build.TAGS;
if ((isEmulator || str == null || !str.contains("test-keys")) && !new File("/system/app/Superuser.apk").exists()) {
return !isEmulator && new File("/system/xbin/su").exists();
}
return true;
}
public static boolean nullSafeEquals(String str, String str2) {
return str == null ? str2 == null : str.equals(str2);
}
public static String padWithZerosToMaxIntWidth(int i) {
if (i >= 0) {
return String.format(Locale.US, "%1$10s", Integer.valueOf(i)).replace(' ', '0');
}
throw new IllegalArgumentException("value must be zero or greater");
}
public static String sha1(String str) {
return hash(str, SHA1_INSTANCE);
}
public static String streamToString(InputStream inputStream) {
Scanner useDelimiter = new Scanner(inputStream).useDelimiter("\\A");
return useDelimiter.hasNext() ? useDelimiter.next() : "";
}
private static String hash(byte[] bArr, String str) {
try {
MessageDigest messageDigest = MessageDigest.getInstance(str);
messageDigest.update(bArr);
return hexify(messageDigest.digest());
} catch (NoSuchAlgorithmException e4) {
Logger.getLogger().e("Could not create hashing algorithm: " + str + ", returning empty string.", e4);
return "";
}
}
}

View File

@@ -0,0 +1,74 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.persistence.FileStore;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
/* loaded from: classes3.dex */
public class CrashlyticsAppQualitySessionsStore {
private static final String AQS_SESSION_ID_FILENAME_PREFIX = "aqs.";
private static final FilenameFilter AQS_SESSION_ID_FILE_FILTER = new a(0);
private static final Comparator<File> FILE_RECENCY_COMPARATOR = new b(0);
private final FileStore fileStore;
private String sessionId = null;
private String appQualitySessionId = null;
public CrashlyticsAppQualitySessionsStore(FileStore fileStore) {
this.fileStore = fileStore;
}
public static /* synthetic */ boolean lambda$static$0(File file, String str) {
return str.startsWith(AQS_SESSION_ID_FILENAME_PREFIX);
}
public static /* synthetic */ int lambda$static$1(File file, File file2) {
return Long.compare(file2.lastModified(), file.lastModified());
}
private static void persist(FileStore fileStore, String str, String str2) {
if (str == null || str2 == null) {
return;
}
try {
fileStore.getSessionFile(str, AQS_SESSION_ID_FILENAME_PREFIX.concat(str2)).createNewFile();
} catch (IOException e4) {
Logger.getLogger().w("Failed to persist App Quality Sessions session id.", e4);
}
}
public static String readAqsSessionIdFile(FileStore fileStore, String str) {
List<File> sessionFiles = fileStore.getSessionFiles(str, AQS_SESSION_ID_FILE_FILTER);
if (!sessionFiles.isEmpty()) {
return ((File) Collections.min(sessionFiles, FILE_RECENCY_COMPARATOR)).getName().substring(4);
}
Logger.getLogger().w("Unable to read App Quality Sessions session id.");
return null;
}
public synchronized String getAppQualitySessionId(String str) {
if (Objects.equals(this.sessionId, str)) {
return this.appQualitySessionId;
}
return readAqsSessionIdFile(this.fileStore, str);
}
public synchronized void rotateAppQualitySessionId(String str) {
if (!Objects.equals(this.appQualitySessionId, str)) {
persist(this.fileStore, this.sessionId, str);
this.appQualitySessionId = str;
}
}
public synchronized void rotateSessionId(String str) {
if (!Objects.equals(this.sessionId, str)) {
persist(this.fileStore, str, this.appQualitySessionId);
this.sessionId = str;
}
}
}

View File

@@ -0,0 +1,40 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.persistence.FileStore;
import com.google.firebase.sessions.api.SessionSubscriber;
/* loaded from: classes3.dex */
public class CrashlyticsAppQualitySessionsSubscriber implements SessionSubscriber {
private final CrashlyticsAppQualitySessionsStore appQualitySessionsStore;
private final DataCollectionArbiter dataCollectionArbiter;
public CrashlyticsAppQualitySessionsSubscriber(DataCollectionArbiter dataCollectionArbiter, FileStore fileStore) {
this.dataCollectionArbiter = dataCollectionArbiter;
this.appQualitySessionsStore = new CrashlyticsAppQualitySessionsStore(fileStore);
}
public String getAppQualitySessionId(String str) {
return this.appQualitySessionsStore.getAppQualitySessionId(str);
}
@Override // com.google.firebase.sessions.api.SessionSubscriber
public SessionSubscriber.Name getSessionSubscriberName() {
return SessionSubscriber.Name.CRASHLYTICS;
}
@Override // com.google.firebase.sessions.api.SessionSubscriber
public boolean isDataCollectionEnabled() {
return this.dataCollectionArbiter.isAutomaticDataCollectionEnabled();
}
@Override // com.google.firebase.sessions.api.SessionSubscriber
public void onSessionChanged(SessionSubscriber.SessionDetails sessionDetails) {
Logger.getLogger().d("App Quality Sessions session changed: " + sessionDetails);
this.appQualitySessionsStore.rotateAppQualitySessionId(sessionDetails.getSessionId());
}
public void setSessionId(String str) {
this.appQualitySessionsStore.rotateSessionId(str);
}
}

View File

@@ -0,0 +1,85 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
/* loaded from: classes3.dex */
public class CrashlyticsBackgroundWorker {
private final Executor executor;
private Task<Void> tail = Tasks.forResult(null);
private final Object tailLock = new Object();
private final ThreadLocal<Boolean> isExecutorThread = new ThreadLocal<>();
public CrashlyticsBackgroundWorker(Executor executor) {
this.executor = executor;
executor.execute(new Runnable() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsBackgroundWorker.1
@Override // java.lang.Runnable
public void run() {
CrashlyticsBackgroundWorker.this.isExecutorThread.set(Boolean.TRUE);
}
});
}
private <T> Task<Void> ignoreResult(Task<T> task) {
return task.continueWith(this.executor, new Continuation<T, Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsBackgroundWorker.4
@Override // com.google.android.gms.tasks.Continuation
public Void then(Task<T> task2) throws Exception {
return null;
}
});
}
private boolean isRunningOnThread() {
return Boolean.TRUE.equals(this.isExecutorThread.get());
}
private <T> Continuation<Void, T> newContinuation(final Callable<T> callable) {
return new Continuation<Void, T>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsBackgroundWorker.3
@Override // com.google.android.gms.tasks.Continuation
public T then(Task<Void> task) throws Exception {
return (T) callable.call();
}
};
}
public void checkRunningOnThread() {
if (!isRunningOnThread()) {
throw new IllegalStateException("Not running on background worker thread as intended.");
}
}
public Executor getExecutor() {
return this.executor;
}
public Task<Void> submit(final Runnable runnable) {
return submit(new Callable<Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsBackgroundWorker.2
@Override // java.util.concurrent.Callable
public Void call() throws Exception {
runnable.run();
return null;
}
});
}
public <T> Task<T> submitTask(Callable<Task<T>> callable) {
Task<T> continueWithTask;
synchronized (this.tailLock) {
continueWithTask = this.tail.continueWithTask(this.executor, newContinuation(callable));
this.tail = ignoreResult(continueWithTask);
}
return continueWithTask;
}
public <T> Task<T> submit(Callable<T> callable) {
Task<T> continueWith;
synchronized (this.tailLock) {
continueWith = this.tail.continueWith(this.executor, newContinuation(callable));
this.tail = ignoreResult(continueWith);
}
return continueWith;
}
}

View File

@@ -0,0 +1,996 @@
package com.google.firebase.crashlytics.internal.common;
import C.w;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ApplicationExitInfo;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.util.Base64;
import com.google.android.gms.tasks.SuccessContinuation;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.crashlytics.internal.CrashlyticsNativeComponent;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.NativeSessionFileProvider;
import com.google.firebase.crashlytics.internal.analytics.AnalyticsEventLogger;
import com.google.firebase.crashlytics.internal.common.CrashlyticsUncaughtExceptionHandler;
import com.google.firebase.crashlytics.internal.metadata.LogFileManager;
import com.google.firebase.crashlytics.internal.metadata.UserMetadata;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import com.google.firebase.crashlytics.internal.model.StaticSessionData;
import com.google.firebase.crashlytics.internal.persistence.FileStore;
import com.google.firebase.crashlytics.internal.settings.Settings;
import com.google.firebase.crashlytics.internal.settings.SettingsProvider;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedSet;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/* loaded from: classes3.dex */
public class CrashlyticsController {
static final FilenameFilter APP_EXCEPTION_MARKER_FILTER = new a(1);
static final String APP_EXCEPTION_MARKER_PREFIX = ".ae";
static final String FIREBASE_APPLICATION_EXCEPTION = "_ae";
static final String FIREBASE_CRASH_TYPE = "fatal";
static final int FIREBASE_CRASH_TYPE_FATAL = 1;
static final String FIREBASE_TIMESTAMP = "timestamp";
private static final String GENERATOR_FORMAT = "Crashlytics Android SDK/%s";
private static final String META_INF_FOLDER = "META-INF/";
static final String NATIVE_SESSION_DIR = "native-sessions";
private static final String VERSION_CONTROL_INFO_FILE = "version-control-info.textproto";
private static final String VERSION_CONTROL_INFO_KEY = "com.crashlytics.version-control-info";
private final AnalyticsEventLogger analyticsEventLogger;
private final AppData appData;
private final CrashlyticsBackgroundWorker backgroundWorker;
private final Context context;
private CrashlyticsUncaughtExceptionHandler crashHandler;
private final CrashlyticsFileMarker crashMarker;
private final DataCollectionArbiter dataCollectionArbiter;
private final FileStore fileStore;
private final IdManager idManager;
private final LogFileManager logFileManager;
private final CrashlyticsNativeComponent nativeComponent;
private final SessionReportingCoordinator reportingCoordinator;
private final CrashlyticsAppQualitySessionsSubscriber sessionsSubscriber;
private final UserMetadata userMetadata;
private SettingsProvider settingsProvider = null;
final TaskCompletionSource<Boolean> unsentReportsAvailable = new TaskCompletionSource<>();
final TaskCompletionSource<Boolean> reportActionProvided = new TaskCompletionSource<>();
final TaskCompletionSource<Void> unsentReportsHandled = new TaskCompletionSource<>();
final AtomicBoolean checkForUnsentReportsCalled = new AtomicBoolean(false);
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$1 */
/* loaded from: classes3.dex */
public class AnonymousClass1 implements CrashlyticsUncaughtExceptionHandler.CrashListener {
public AnonymousClass1() {
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsUncaughtExceptionHandler.CrashListener
public void onUncaughtException(SettingsProvider settingsProvider, Thread thread, Throwable th) {
CrashlyticsController.this.handleUncaughtException(settingsProvider, thread, th);
}
}
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$2 */
/* loaded from: classes3.dex */
public class AnonymousClass2 implements Callable<Task<Void>> {
final /* synthetic */ Throwable val$ex;
final /* synthetic */ boolean val$isOnDemand;
final /* synthetic */ SettingsProvider val$settingsProvider;
final /* synthetic */ Thread val$thread;
final /* synthetic */ long val$timestampMillis;
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$2$1 */
/* loaded from: classes3.dex */
public class AnonymousClass1 implements SuccessContinuation<Settings, Void> {
final /* synthetic */ String val$currentSessionId;
final /* synthetic */ Executor val$executor;
public AnonymousClass1(Executor executor, String str) {
r2 = executor;
r3 = str;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings, cannot send reports at crash time.");
return Tasks.forResult(null);
}
return Tasks.whenAll((Task<?>[]) new Task[]{CrashlyticsController.this.logAnalyticsAppExceptionEvents(), CrashlyticsController.this.reportingCoordinator.sendReports(r2, r7 ? r3 : null)});
}
}
public AnonymousClass2(long j4, Throwable th, Thread thread, SettingsProvider settingsProvider, boolean z3) {
r2 = j4;
r4 = th;
r5 = thread;
r6 = settingsProvider;
r7 = z3;
}
@Override // java.util.concurrent.Callable
public Task<Void> call() throws Exception {
long timestampSeconds = CrashlyticsController.getTimestampSeconds(r2);
String currentSessionId = CrashlyticsController.this.getCurrentSessionId();
if (currentSessionId == null) {
Logger.getLogger().e("Tried to write a fatal exception while no session was open.");
return Tasks.forResult(null);
}
CrashlyticsController.this.crashMarker.create();
CrashlyticsController.this.reportingCoordinator.persistFatalEvent(r4, r5, currentSessionId, timestampSeconds);
CrashlyticsController.this.doWriteAppExceptionMarker(r2);
CrashlyticsController.this.doCloseSessions(r6);
CrashlyticsController.this.doOpenSession(new CLSUUID(CrashlyticsController.this.idManager).toString(), Boolean.valueOf(r7));
if (!CrashlyticsController.this.dataCollectionArbiter.isAutomaticDataCollectionEnabled()) {
return Tasks.forResult(null);
}
Executor executor = CrashlyticsController.this.backgroundWorker.getExecutor();
return r6.getSettingsAsync().onSuccessTask(executor, new SuccessContinuation<Settings, Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.2.1
final /* synthetic */ String val$currentSessionId;
final /* synthetic */ Executor val$executor;
public AnonymousClass1(Executor executor2, String currentSessionId2) {
r2 = executor2;
r3 = currentSessionId2;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings, cannot send reports at crash time.");
return Tasks.forResult(null);
}
return Tasks.whenAll((Task<?>[]) new Task[]{CrashlyticsController.this.logAnalyticsAppExceptionEvents(), CrashlyticsController.this.reportingCoordinator.sendReports(r2, r7 ? r3 : null)});
}
});
}
}
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$3 */
/* loaded from: classes3.dex */
public class AnonymousClass3 implements SuccessContinuation<Void, Boolean> {
public AnonymousClass3() {
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Boolean> then(Void r12) throws Exception {
return Tasks.forResult(Boolean.TRUE);
}
}
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$4 */
/* loaded from: classes3.dex */
public class AnonymousClass4 implements SuccessContinuation<Boolean, Void> {
final /* synthetic */ Task val$settingsDataTask;
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$4$1 */
/* loaded from: classes3.dex */
public class AnonymousClass1 implements Callable<Task<Void>> {
final /* synthetic */ Boolean val$send;
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$4$1$1 */
/* loaded from: classes3.dex */
public class C00161 implements SuccessContinuation<Settings, Void> {
final /* synthetic */ Executor val$executor;
public C00161(Executor executor) {
r2 = executor;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings at app startup. Cannot send cached reports");
return Tasks.forResult(null);
}
CrashlyticsController.this.logAnalyticsAppExceptionEvents();
CrashlyticsController.this.reportingCoordinator.sendReports(r2);
CrashlyticsController.this.unsentReportsHandled.trySetResult(null);
return Tasks.forResult(null);
}
}
public AnonymousClass1(Boolean bool) {
r2 = bool;
}
@Override // java.util.concurrent.Callable
public Task<Void> call() throws Exception {
if (!r2.booleanValue()) {
Logger.getLogger().v("Deleting cached crash reports...");
CrashlyticsController.deleteFiles(CrashlyticsController.this.listAppExceptionMarkerFiles());
CrashlyticsController.this.reportingCoordinator.removeAllReports();
CrashlyticsController.this.unsentReportsHandled.trySetResult(null);
return Tasks.forResult(null);
}
Logger.getLogger().d("Sending cached crash reports...");
CrashlyticsController.this.dataCollectionArbiter.grantDataCollectionPermission(r2.booleanValue());
Executor executor = CrashlyticsController.this.backgroundWorker.getExecutor();
return AnonymousClass4.this.val$settingsDataTask.onSuccessTask(executor, new SuccessContinuation<Settings, Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.4.1.1
final /* synthetic */ Executor val$executor;
public C00161(Executor executor2) {
r2 = executor2;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings at app startup. Cannot send cached reports");
return Tasks.forResult(null);
}
CrashlyticsController.this.logAnalyticsAppExceptionEvents();
CrashlyticsController.this.reportingCoordinator.sendReports(r2);
CrashlyticsController.this.unsentReportsHandled.trySetResult(null);
return Tasks.forResult(null);
}
});
}
}
public AnonymousClass4(Task task) {
this.val$settingsDataTask = task;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Boolean bool) throws Exception {
return CrashlyticsController.this.backgroundWorker.submitTask(new Callable<Task<Void>>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.4.1
final /* synthetic */ Boolean val$send;
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$4$1$1 */
/* loaded from: classes3.dex */
public class C00161 implements SuccessContinuation<Settings, Void> {
final /* synthetic */ Executor val$executor;
public C00161(Executor executor2) {
r2 = executor2;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings at app startup. Cannot send cached reports");
return Tasks.forResult(null);
}
CrashlyticsController.this.logAnalyticsAppExceptionEvents();
CrashlyticsController.this.reportingCoordinator.sendReports(r2);
CrashlyticsController.this.unsentReportsHandled.trySetResult(null);
return Tasks.forResult(null);
}
}
public AnonymousClass1(Boolean bool2) {
r2 = bool2;
}
@Override // java.util.concurrent.Callable
public Task<Void> call() throws Exception {
if (!r2.booleanValue()) {
Logger.getLogger().v("Deleting cached crash reports...");
CrashlyticsController.deleteFiles(CrashlyticsController.this.listAppExceptionMarkerFiles());
CrashlyticsController.this.reportingCoordinator.removeAllReports();
CrashlyticsController.this.unsentReportsHandled.trySetResult(null);
return Tasks.forResult(null);
}
Logger.getLogger().d("Sending cached crash reports...");
CrashlyticsController.this.dataCollectionArbiter.grantDataCollectionPermission(r2.booleanValue());
Executor executor2 = CrashlyticsController.this.backgroundWorker.getExecutor();
return AnonymousClass4.this.val$settingsDataTask.onSuccessTask(executor2, new SuccessContinuation<Settings, Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.4.1.1
final /* synthetic */ Executor val$executor;
public C00161(Executor executor22) {
r2 = executor22;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings at app startup. Cannot send cached reports");
return Tasks.forResult(null);
}
CrashlyticsController.this.logAnalyticsAppExceptionEvents();
CrashlyticsController.this.reportingCoordinator.sendReports(r2);
CrashlyticsController.this.unsentReportsHandled.trySetResult(null);
return Tasks.forResult(null);
}
});
}
});
}
}
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$5 */
/* loaded from: classes3.dex */
public class AnonymousClass5 implements Callable<Void> {
final /* synthetic */ String val$msg;
final /* synthetic */ long val$timestamp;
public AnonymousClass5(long j4, String str) {
r2 = j4;
r4 = str;
}
@Override // java.util.concurrent.Callable
public Void call() throws Exception {
if (CrashlyticsController.this.isHandlingException()) {
return null;
}
CrashlyticsController.this.logFileManager.writeToLog(r2, r4);
return null;
}
}
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$6 */
/* loaded from: classes3.dex */
public class AnonymousClass6 implements Runnable {
final /* synthetic */ Throwable val$ex;
final /* synthetic */ Thread val$thread;
final /* synthetic */ long val$timestampMillis;
public AnonymousClass6(long j4, Throwable th, Thread thread) {
r2 = j4;
r4 = th;
r5 = thread;
}
@Override // java.lang.Runnable
public void run() {
if (CrashlyticsController.this.isHandlingException()) {
return;
}
long timestampSeconds = CrashlyticsController.getTimestampSeconds(r2);
String currentSessionId = CrashlyticsController.this.getCurrentSessionId();
if (currentSessionId == null) {
Logger.getLogger().w("Tried to write a non-fatal exception while no session was open.");
} else {
CrashlyticsController.this.reportingCoordinator.persistNonFatalEvent(r4, r5, currentSessionId, timestampSeconds);
}
}
}
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$7 */
/* loaded from: classes3.dex */
public class AnonymousClass7 implements Callable<Void> {
final /* synthetic */ String val$sessionIdentifier;
public AnonymousClass7(String str) {
r2 = str;
}
@Override // java.util.concurrent.Callable
public Void call() throws Exception {
CrashlyticsController.this.doOpenSession(r2, Boolean.FALSE);
return null;
}
}
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$8 */
/* loaded from: classes3.dex */
public class AnonymousClass8 implements Callable<Void> {
final /* synthetic */ long val$timestamp;
public AnonymousClass8(long j4) {
r2 = j4;
}
@Override // java.util.concurrent.Callable
public Void call() throws Exception {
Bundle bundle = new Bundle();
bundle.putInt(CrashlyticsController.FIREBASE_CRASH_TYPE, 1);
bundle.putLong(CrashlyticsController.FIREBASE_TIMESTAMP, r2);
CrashlyticsController.this.analyticsEventLogger.logEvent(CrashlyticsController.FIREBASE_APPLICATION_EXCEPTION, bundle);
return null;
}
}
public CrashlyticsController(Context context, CrashlyticsBackgroundWorker crashlyticsBackgroundWorker, IdManager idManager, DataCollectionArbiter dataCollectionArbiter, FileStore fileStore, CrashlyticsFileMarker crashlyticsFileMarker, AppData appData, UserMetadata userMetadata, LogFileManager logFileManager, SessionReportingCoordinator sessionReportingCoordinator, CrashlyticsNativeComponent crashlyticsNativeComponent, AnalyticsEventLogger analyticsEventLogger, CrashlyticsAppQualitySessionsSubscriber crashlyticsAppQualitySessionsSubscriber) {
this.context = context;
this.backgroundWorker = crashlyticsBackgroundWorker;
this.idManager = idManager;
this.dataCollectionArbiter = dataCollectionArbiter;
this.fileStore = fileStore;
this.crashMarker = crashlyticsFileMarker;
this.appData = appData;
this.userMetadata = userMetadata;
this.logFileManager = logFileManager;
this.nativeComponent = crashlyticsNativeComponent;
this.analyticsEventLogger = analyticsEventLogger;
this.sessionsSubscriber = crashlyticsAppQualitySessionsSubscriber;
this.reportingCoordinator = sessionReportingCoordinator;
}
private static StaticSessionData.AppData createAppData(IdManager idManager, AppData appData) {
return StaticSessionData.AppData.create(idManager.getAppIdentifier(), appData.versionCode, appData.versionName, idManager.getInstallIds().getCrashlyticsInstallId(), DeliveryMechanism.determineFrom(appData.installerPackageName).getId(), appData.developmentPlatformProvider);
}
private static StaticSessionData.DeviceData createDeviceData(Context context) {
StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
return StaticSessionData.DeviceData.create(CommonUtils.getCpuArchitectureInt(), Build.MODEL, Runtime.getRuntime().availableProcessors(), CommonUtils.calculateTotalRamInBytes(context), statFs.getBlockCount() * statFs.getBlockSize(), CommonUtils.isEmulator(), CommonUtils.getDeviceState(), Build.MANUFACTURER, Build.PRODUCT);
}
private static StaticSessionData.OsData createOsData() {
return StaticSessionData.OsData.create(Build.VERSION.RELEASE, Build.VERSION.CODENAME, CommonUtils.isRooted());
}
public static void deleteFiles(List<File> list) {
Iterator<File> it = list.iterator();
while (it.hasNext()) {
it.next().delete();
}
}
public void doOpenSession(String str, Boolean bool) {
long currentTimestampSeconds = getCurrentTimestampSeconds();
Logger.getLogger().d("Opening a new session with ID " + str);
Locale locale = Locale.US;
this.nativeComponent.prepareNativeSession(str, w.z("Crashlytics Android SDK/", CrashlyticsCore.getVersion()), currentTimestampSeconds, StaticSessionData.create(createAppData(this.idManager, this.appData), createOsData(), createDeviceData(this.context)));
if (bool.booleanValue() && str != null) {
this.userMetadata.setNewSession(str);
}
this.logFileManager.setCurrentSession(str);
this.sessionsSubscriber.setSessionId(str);
this.reportingCoordinator.onBeginSession(str, currentTimestampSeconds);
}
public void doWriteAppExceptionMarker(long j4) {
try {
if (this.fileStore.getCommonFile(APP_EXCEPTION_MARKER_PREFIX + j4).createNewFile()) {
} else {
throw new IOException("Create new file failed.");
}
} catch (IOException e4) {
Logger.getLogger().w("Could not create app exception marker file.", e4);
}
}
private void finalizePreviousNativeSession(String str) {
Logger.getLogger().v("Finalizing native report for session " + str);
NativeSessionFileProvider sessionFileProvider = this.nativeComponent.getSessionFileProvider(str);
File minidumpFile = sessionFileProvider.getMinidumpFile();
CrashlyticsReport.ApplicationExitInfo applicationExitInto = sessionFileProvider.getApplicationExitInto();
if (nativeCoreAbsent(str, minidumpFile, applicationExitInto)) {
Logger.getLogger().w("No native core present");
return;
}
long lastModified = minidumpFile.lastModified();
LogFileManager logFileManager = new LogFileManager(this.fileStore, str);
File nativeSessionDir = this.fileStore.getNativeSessionDir(str);
if (!nativeSessionDir.isDirectory()) {
Logger.getLogger().w("Couldn't create directory to store native session files, aborting.");
return;
}
doWriteAppExceptionMarker(lastModified);
List<NativeSessionFile> nativeSessionFiles = getNativeSessionFiles(sessionFileProvider, str, this.fileStore, logFileManager.getBytesForLog());
NativeSessionFileGzipper.processNativeSessions(nativeSessionDir, nativeSessionFiles);
Logger.getLogger().d("CrashlyticsController#finalizePreviousNativeSession");
this.reportingCoordinator.finalizeSessionWithNativeEvent(str, nativeSessionFiles, applicationExitInto);
logFileManager.clearLog();
}
private static boolean firebaseCrashExists() {
try {
Class.forName("com.google.firebase.crash.FirebaseCrash");
return true;
} catch (ClassNotFoundException unused) {
return false;
}
}
private Context getContext() {
return this.context;
}
public String getCurrentSessionId() {
SortedSet<String> listSortedOpenSessionIds = this.reportingCoordinator.listSortedOpenSessionIds();
if (listSortedOpenSessionIds.isEmpty()) {
return null;
}
return listSortedOpenSessionIds.first();
}
private static long getCurrentTimestampSeconds() {
return getTimestampSeconds(System.currentTimeMillis());
}
public static List<NativeSessionFile> getNativeSessionFiles(NativeSessionFileProvider nativeSessionFileProvider, String str, FileStore fileStore, byte[] bArr) {
File sessionFile = fileStore.getSessionFile(str, UserMetadata.USERDATA_FILENAME);
File sessionFile2 = fileStore.getSessionFile(str, UserMetadata.KEYDATA_FILENAME);
File sessionFile3 = fileStore.getSessionFile(str, UserMetadata.ROLLOUTS_STATE_FILENAME);
ArrayList arrayList = new ArrayList();
arrayList.add(new BytesBackedNativeSessionFile("logs_file", "logs", bArr));
arrayList.add(new FileBackedNativeSessionFile("crash_meta_file", "metadata", nativeSessionFileProvider.getMetadataFile()));
arrayList.add(new FileBackedNativeSessionFile("session_meta_file", "session", nativeSessionFileProvider.getSessionFile()));
arrayList.add(new FileBackedNativeSessionFile("app_meta_file", "app", nativeSessionFileProvider.getAppFile()));
arrayList.add(new FileBackedNativeSessionFile("device_meta_file", "device", nativeSessionFileProvider.getDeviceFile()));
arrayList.add(new FileBackedNativeSessionFile("os_meta_file", "os", nativeSessionFileProvider.getOsFile()));
arrayList.add(nativeCoreFile(nativeSessionFileProvider));
arrayList.add(new FileBackedNativeSessionFile("user_meta_file", "user", sessionFile));
arrayList.add(new FileBackedNativeSessionFile("keys_file", UserMetadata.KEYDATA_FILENAME, sessionFile2));
arrayList.add(new FileBackedNativeSessionFile("rollouts_file", "rollouts", sessionFile3));
return arrayList;
}
private InputStream getResourceAsStream(String str) {
ClassLoader classLoader = getClass().getClassLoader();
if (classLoader == null) {
Logger.getLogger().w("Couldn't get Class Loader");
return null;
}
InputStream resourceAsStream = classLoader.getResourceAsStream(str);
if (resourceAsStream != null) {
return resourceAsStream;
}
Logger.getLogger().i("No version control information found");
return null;
}
public static long getTimestampSeconds(long j4) {
return j4 / 1000;
}
public static /* synthetic */ boolean lambda$static$0(File file, String str) {
return str.startsWith(APP_EXCEPTION_MARKER_PREFIX);
}
private Task<Void> logAnalyticsAppExceptionEvent(long j4) {
if (firebaseCrashExists()) {
Logger.getLogger().w("Skipping logging Crashlytics event to Firebase, FirebaseCrash exists");
return Tasks.forResult(null);
}
Logger.getLogger().d("Logging app exception event to Firebase Analytics");
return Tasks.call(new ScheduledThreadPoolExecutor(1), new Callable<Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.8
final /* synthetic */ long val$timestamp;
public AnonymousClass8(long j42) {
r2 = j42;
}
@Override // java.util.concurrent.Callable
public Void call() throws Exception {
Bundle bundle = new Bundle();
bundle.putInt(CrashlyticsController.FIREBASE_CRASH_TYPE, 1);
bundle.putLong(CrashlyticsController.FIREBASE_TIMESTAMP, r2);
CrashlyticsController.this.analyticsEventLogger.logEvent(CrashlyticsController.FIREBASE_APPLICATION_EXCEPTION, bundle);
return null;
}
});
}
public Task<Void> logAnalyticsAppExceptionEvents() {
ArrayList arrayList = new ArrayList();
for (File file : listAppExceptionMarkerFiles()) {
try {
arrayList.add(logAnalyticsAppExceptionEvent(Long.parseLong(file.getName().substring(3))));
} catch (NumberFormatException unused) {
Logger.getLogger().w("Could not parse app exception timestamp from file " + file.getName());
}
file.delete();
}
return Tasks.whenAll(arrayList);
}
private static boolean nativeCoreAbsent(String str, File file, CrashlyticsReport.ApplicationExitInfo applicationExitInfo) {
if (file == null || !file.exists()) {
Logger.getLogger().w("No minidump data found for session " + str);
}
if (applicationExitInfo == null) {
Logger.getLogger().i("No Tombstones data found for session " + str);
}
return (file == null || !file.exists()) && applicationExitInfo == null;
}
private static NativeSessionFile nativeCoreFile(NativeSessionFileProvider nativeSessionFileProvider) {
File minidumpFile = nativeSessionFileProvider.getMinidumpFile();
return (minidumpFile == null || !minidumpFile.exists()) ? new BytesBackedNativeSessionFile("minidump_file", "minidump", new byte[]{0}) : new FileBackedNativeSessionFile("minidump_file", "minidump", minidumpFile);
}
private static byte[] readResource(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bArr = new byte[1024];
while (true) {
int read = inputStream.read(bArr);
if (read == -1) {
return byteArrayOutputStream.toByteArray();
}
byteArrayOutputStream.write(bArr, 0, read);
}
}
private Task<Boolean> waitForReportAction() {
if (this.dataCollectionArbiter.isAutomaticDataCollectionEnabled()) {
Logger.getLogger().d("Automatic data collection is enabled. Allowing upload.");
this.unsentReportsAvailable.trySetResult(Boolean.FALSE);
return Tasks.forResult(Boolean.TRUE);
}
Logger.getLogger().d("Automatic data collection is disabled.");
Logger.getLogger().v("Notifying that unsent reports are available.");
this.unsentReportsAvailable.trySetResult(Boolean.TRUE);
Task<TContinuationResult> onSuccessTask = this.dataCollectionArbiter.waitForAutomaticDataCollectionEnabled().onSuccessTask(new SuccessContinuation<Void, Boolean>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.3
public AnonymousClass3() {
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Boolean> then(Void r12) throws Exception {
return Tasks.forResult(Boolean.TRUE);
}
});
Logger.getLogger().d("Waiting for send/deleteUnsentReports to be called.");
return Utils.race(onSuccessTask, this.reportActionProvided.getTask());
}
private void writeApplicationExitInfoEventIfRelevant(String str) {
List<ApplicationExitInfo> historicalProcessExitReasons;
int i = Build.VERSION.SDK_INT;
if (i < 30) {
Logger.getLogger().v("ANR feature enabled, but device is API " + i);
return;
}
historicalProcessExitReasons = ((ActivityManager) this.context.getSystemService("activity")).getHistoricalProcessExitReasons(null, 0, 0);
if (historicalProcessExitReasons.size() != 0) {
this.reportingCoordinator.persistRelevantAppExitInfoEvent(str, historicalProcessExitReasons, new LogFileManager(this.fileStore, str), UserMetadata.loadFromExistingSession(str, this.fileStore, this.backgroundWorker));
} else {
Logger.getLogger().v("No ApplicationExitInfo available. Session: " + str);
}
}
public Task<Boolean> checkForUnsentReports() {
if (this.checkForUnsentReportsCalled.compareAndSet(false, true)) {
return this.unsentReportsAvailable.getTask();
}
Logger.getLogger().w("checkForUnsentReports should only be called once per execution.");
return Tasks.forResult(Boolean.FALSE);
}
public Task<Void> deleteUnsentReports() {
this.reportActionProvided.trySetResult(Boolean.FALSE);
return this.unsentReportsHandled.getTask();
}
public boolean didCrashOnPreviousExecution() {
if (!this.crashMarker.isPresent()) {
String currentSessionId = getCurrentSessionId();
return currentSessionId != null && this.nativeComponent.hasCrashDataForSession(currentSessionId);
}
Logger.getLogger().v("Found previous crash marker.");
this.crashMarker.remove();
return true;
}
public void doCloseSessions(SettingsProvider settingsProvider) {
doCloseSessions(false, settingsProvider);
}
public void enableExceptionHandling(String str, Thread.UncaughtExceptionHandler uncaughtExceptionHandler, SettingsProvider settingsProvider) {
this.settingsProvider = settingsProvider;
openSession(str);
CrashlyticsUncaughtExceptionHandler crashlyticsUncaughtExceptionHandler = new CrashlyticsUncaughtExceptionHandler(new CrashlyticsUncaughtExceptionHandler.CrashListener() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.1
public AnonymousClass1() {
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsUncaughtExceptionHandler.CrashListener
public void onUncaughtException(SettingsProvider settingsProvider2, Thread thread, Throwable th) {
CrashlyticsController.this.handleUncaughtException(settingsProvider2, thread, th);
}
}, settingsProvider, uncaughtExceptionHandler, this.nativeComponent);
this.crashHandler = crashlyticsUncaughtExceptionHandler;
Thread.setDefaultUncaughtExceptionHandler(crashlyticsUncaughtExceptionHandler);
}
public boolean finalizeSessions(SettingsProvider settingsProvider) {
this.backgroundWorker.checkRunningOnThread();
if (isHandlingException()) {
Logger.getLogger().w("Skipping session finalization because a crash has already occurred.");
return false;
}
Logger.getLogger().v("Finalizing previously open sessions.");
try {
doCloseSessions(true, settingsProvider);
Logger.getLogger().v("Closed all previously open sessions.");
return true;
} catch (Exception e4) {
Logger.getLogger().e("Unable to finalize previously open sessions.", e4);
return false;
}
}
public UserMetadata getUserMetadata() {
return this.userMetadata;
}
public String getVersionControlInfo() throws IOException {
InputStream resourceAsStream = getResourceAsStream("META-INF/version-control-info.textproto");
if (resourceAsStream == null) {
return null;
}
Logger.getLogger().d("Read version control info");
return Base64.encodeToString(readResource(resourceAsStream), 0);
}
public void handleUncaughtException(SettingsProvider settingsProvider, Thread thread, Throwable th) {
handleUncaughtException(settingsProvider, thread, th, false);
}
public boolean isHandlingException() {
CrashlyticsUncaughtExceptionHandler crashlyticsUncaughtExceptionHandler = this.crashHandler;
return crashlyticsUncaughtExceptionHandler != null && crashlyticsUncaughtExceptionHandler.isHandlingException();
}
public List<File> listAppExceptionMarkerFiles() {
return this.fileStore.getCommonFiles(APP_EXCEPTION_MARKER_FILTER);
}
public void logFatalException(Thread thread, Throwable th) {
SettingsProvider settingsProvider = this.settingsProvider;
if (settingsProvider == null) {
Logger.getLogger().w("settingsProvider not set");
} else {
handleUncaughtException(settingsProvider, thread, th, true);
}
}
public void openSession(String str) {
this.backgroundWorker.submit(new Callable<Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.7
final /* synthetic */ String val$sessionIdentifier;
public AnonymousClass7(String str2) {
r2 = str2;
}
@Override // java.util.concurrent.Callable
public Void call() throws Exception {
CrashlyticsController.this.doOpenSession(r2, Boolean.FALSE);
return null;
}
});
}
public void saveVersionControlInfo() {
try {
String versionControlInfo = getVersionControlInfo();
if (versionControlInfo != null) {
setInternalKey(VERSION_CONTROL_INFO_KEY, versionControlInfo);
Logger.getLogger().i("Saved version control info");
}
} catch (IOException e4) {
Logger.getLogger().w("Unable to save version control info", e4);
}
}
public Task<Void> sendUnsentReports() {
this.reportActionProvided.trySetResult(Boolean.TRUE);
return this.unsentReportsHandled.getTask();
}
public void setCustomKey(String str, String str2) {
try {
this.userMetadata.setCustomKey(str, str2);
} catch (IllegalArgumentException e4) {
Context context = this.context;
if (context != null && CommonUtils.isAppDebuggable(context)) {
throw e4;
}
Logger.getLogger().e("Attempting to set custom attribute with null key, ignoring.");
}
}
public void setCustomKeys(Map<String, String> map) {
this.userMetadata.setCustomKeys(map);
}
public void setInternalKey(String str, String str2) {
try {
this.userMetadata.setInternalKey(str, str2);
} catch (IllegalArgumentException e4) {
Context context = this.context;
if (context != null && CommonUtils.isAppDebuggable(context)) {
throw e4;
}
Logger.getLogger().e("Attempting to set custom attribute with null key, ignoring.");
}
}
public void setUserId(String str) {
this.userMetadata.setUserId(str);
}
@SuppressLint({"TaskMainThread"})
public Task<Void> submitAllReports(Task<Settings> task) {
if (this.reportingCoordinator.hasReportsToSend()) {
Logger.getLogger().v("Crash reports are available to be sent.");
return waitForReportAction().onSuccessTask(new AnonymousClass4(task));
}
Logger.getLogger().v("No crash reports are available to be sent.");
this.unsentReportsAvailable.trySetResult(Boolean.FALSE);
return Tasks.forResult(null);
}
public void writeNonFatalException(Thread thread, Throwable th) {
this.backgroundWorker.submit(new Runnable() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.6
final /* synthetic */ Throwable val$ex;
final /* synthetic */ Thread val$thread;
final /* synthetic */ long val$timestampMillis;
public AnonymousClass6(long j4, Throwable th2, Thread thread2) {
r2 = j4;
r4 = th2;
r5 = thread2;
}
@Override // java.lang.Runnable
public void run() {
if (CrashlyticsController.this.isHandlingException()) {
return;
}
long timestampSeconds = CrashlyticsController.getTimestampSeconds(r2);
String currentSessionId = CrashlyticsController.this.getCurrentSessionId();
if (currentSessionId == null) {
Logger.getLogger().w("Tried to write a non-fatal exception while no session was open.");
} else {
CrashlyticsController.this.reportingCoordinator.persistNonFatalEvent(r4, r5, currentSessionId, timestampSeconds);
}
}
});
}
public void writeToLog(long j4, String str) {
this.backgroundWorker.submit(new Callable<Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.5
final /* synthetic */ String val$msg;
final /* synthetic */ long val$timestamp;
public AnonymousClass5(long j42, String str2) {
r2 = j42;
r4 = str2;
}
@Override // java.util.concurrent.Callable
public Void call() throws Exception {
if (CrashlyticsController.this.isHandlingException()) {
return null;
}
CrashlyticsController.this.logFileManager.writeToLog(r2, r4);
return null;
}
});
}
/* JADX WARN: Multi-variable type inference failed */
private void doCloseSessions(boolean z3, SettingsProvider settingsProvider) {
String str;
ArrayList arrayList = new ArrayList(this.reportingCoordinator.listSortedOpenSessionIds());
if (arrayList.size() <= z3) {
Logger.getLogger().v("No open sessions to be closed.");
return;
}
String str2 = (String) arrayList.get(z3 ? 1 : 0);
if (settingsProvider.getSettingsSync().featureFlagData.collectAnrs) {
writeApplicationExitInfoEventIfRelevant(str2);
} else {
Logger.getLogger().v("ANR feature disabled.");
}
if (this.nativeComponent.hasCrashDataForSession(str2)) {
finalizePreviousNativeSession(str2);
}
if (z3 != 0) {
str = (String) arrayList.get(0);
} else {
this.sessionsSubscriber.setSessionId(null);
str = null;
}
this.reportingCoordinator.finalizeSessions(getCurrentTimestampSeconds(), str);
}
public synchronized void handleUncaughtException(SettingsProvider settingsProvider, Thread thread, Throwable th, boolean z3) {
CrashlyticsController crashlyticsController;
try {
try {
Logger.getLogger().d("Handling uncaught exception \"" + th + "\" from thread " + thread.getName());
crashlyticsController = this;
try {
Utils.awaitEvenIfOnMainThread(this.backgroundWorker.submitTask(new Callable<Task<Void>>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.2
final /* synthetic */ Throwable val$ex;
final /* synthetic */ boolean val$isOnDemand;
final /* synthetic */ SettingsProvider val$settingsProvider;
final /* synthetic */ Thread val$thread;
final /* synthetic */ long val$timestampMillis;
/* renamed from: com.google.firebase.crashlytics.internal.common.CrashlyticsController$2$1 */
/* loaded from: classes3.dex */
public class AnonymousClass1 implements SuccessContinuation<Settings, Void> {
final /* synthetic */ String val$currentSessionId;
final /* synthetic */ Executor val$executor;
public AnonymousClass1(Executor executor2, String currentSessionId2) {
r2 = executor2;
r3 = currentSessionId2;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings, cannot send reports at crash time.");
return Tasks.forResult(null);
}
return Tasks.whenAll((Task<?>[]) new Task[]{CrashlyticsController.this.logAnalyticsAppExceptionEvents(), CrashlyticsController.this.reportingCoordinator.sendReports(r2, r7 ? r3 : null)});
}
}
public AnonymousClass2(long j4, Throwable th2, Thread thread2, SettingsProvider settingsProvider2, boolean z32) {
r2 = j4;
r4 = th2;
r5 = thread2;
r6 = settingsProvider2;
r7 = z32;
}
@Override // java.util.concurrent.Callable
public Task<Void> call() throws Exception {
long timestampSeconds = CrashlyticsController.getTimestampSeconds(r2);
String currentSessionId2 = CrashlyticsController.this.getCurrentSessionId();
if (currentSessionId2 == null) {
Logger.getLogger().e("Tried to write a fatal exception while no session was open.");
return Tasks.forResult(null);
}
CrashlyticsController.this.crashMarker.create();
CrashlyticsController.this.reportingCoordinator.persistFatalEvent(r4, r5, currentSessionId2, timestampSeconds);
CrashlyticsController.this.doWriteAppExceptionMarker(r2);
CrashlyticsController.this.doCloseSessions(r6);
CrashlyticsController.this.doOpenSession(new CLSUUID(CrashlyticsController.this.idManager).toString(), Boolean.valueOf(r7));
if (!CrashlyticsController.this.dataCollectionArbiter.isAutomaticDataCollectionEnabled()) {
return Tasks.forResult(null);
}
Executor executor2 = CrashlyticsController.this.backgroundWorker.getExecutor();
return r6.getSettingsAsync().onSuccessTask(executor2, new SuccessContinuation<Settings, Void>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsController.2.1
final /* synthetic */ String val$currentSessionId;
final /* synthetic */ Executor val$executor;
public AnonymousClass1(Executor executor22, String currentSessionId22) {
r2 = executor22;
r3 = currentSessionId22;
}
@Override // com.google.android.gms.tasks.SuccessContinuation
public Task<Void> then(Settings settings) throws Exception {
if (settings == null) {
Logger.getLogger().w("Received null app settings, cannot send reports at crash time.");
return Tasks.forResult(null);
}
return Tasks.whenAll((Task<?>[]) new Task[]{CrashlyticsController.this.logAnalyticsAppExceptionEvents(), CrashlyticsController.this.reportingCoordinator.sendReports(r2, r7 ? r3 : null)});
}
});
}
}));
} catch (TimeoutException unused) {
Logger.getLogger().e("Cannot send reports. Timed out while fetching settings.");
} catch (Exception e4) {
Logger.getLogger().e("Error handling uncaught exception", e4);
}
} catch (Throwable th2) {
th = th2;
crashlyticsController = this;
Throwable th3 = th;
throw th3;
}
} catch (Throwable th4) {
th = th4;
}
}
}

View File

@@ -0,0 +1,294 @@
package com.google.firebase.crashlytics.internal.common;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.FirebaseApp;
import com.google.firebase.crashlytics.BuildConfig;
import com.google.firebase.crashlytics.internal.CrashlyticsNativeComponent;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.RemoteConfigDeferredProxy;
import com.google.firebase.crashlytics.internal.analytics.AnalyticsEventLogger;
import com.google.firebase.crashlytics.internal.breadcrumbs.BreadcrumbHandler;
import com.google.firebase.crashlytics.internal.breadcrumbs.BreadcrumbSource;
import com.google.firebase.crashlytics.internal.metadata.LogFileManager;
import com.google.firebase.crashlytics.internal.metadata.UserMetadata;
import com.google.firebase.crashlytics.internal.persistence.FileStore;
import com.google.firebase.crashlytics.internal.settings.SettingsProvider;
import com.google.firebase.crashlytics.internal.stacktrace.MiddleOutFallbackStrategy;
import com.google.firebase.crashlytics.internal.stacktrace.RemoveRepeatsStrategy;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/* loaded from: classes3.dex */
public class CrashlyticsCore {
static final String CRASHLYTICS_REQUIRE_BUILD_ID = "com.crashlytics.RequireBuildId";
static final boolean CRASHLYTICS_REQUIRE_BUILD_ID_DEFAULT = true;
static final String CRASH_MARKER_FILE_NAME = "crash_marker";
static final int DEFAULT_MAIN_HANDLER_TIMEOUT_SEC = 3;
private static final String INITIALIZATION_MARKER_FILE_NAME = "initialization_marker";
static final int MAX_STACK_SIZE = 1024;
private static final String MISSING_BUILD_ID_MSG = "The Crashlytics build ID is missing. This occurs when the Crashlytics Gradle plugin is missing from your app's build configuration. Please review the Firebase Crashlytics onboarding instructions at https://firebase.google.com/docs/crashlytics/get-started?platform=android#add-plugin";
static final int NUM_STACK_REPETITIONS_ALLOWED = 10;
private static final String ON_DEMAND_DROPPED_KEY = "com.crashlytics.on-demand.dropped-exceptions";
private static final String ON_DEMAND_RECORDED_KEY = "com.crashlytics.on-demand.recorded-exceptions";
private final AnalyticsEventLogger analyticsEventLogger;
private final FirebaseApp app;
private final CrashlyticsBackgroundWorker backgroundWorker;
public final BreadcrumbSource breadcrumbSource;
private final Context context;
private CrashlyticsController controller;
private final ExecutorService crashHandlerExecutor;
private CrashlyticsFileMarker crashMarker;
private final DataCollectionArbiter dataCollectionArbiter;
private boolean didCrashOnPreviousExecution;
private final FileStore fileStore;
private final IdManager idManager;
private CrashlyticsFileMarker initializationMarker;
private final CrashlyticsNativeComponent nativeComponent;
private final RemoteConfigDeferredProxy remoteConfigDeferredProxy;
private final CrashlyticsAppQualitySessionsSubscriber sessionsSubscriber;
private final long startTime = System.currentTimeMillis();
private final OnDemandCounter onDemandCounter = new OnDemandCounter();
public CrashlyticsCore(FirebaseApp firebaseApp, IdManager idManager, CrashlyticsNativeComponent crashlyticsNativeComponent, DataCollectionArbiter dataCollectionArbiter, BreadcrumbSource breadcrumbSource, AnalyticsEventLogger analyticsEventLogger, FileStore fileStore, ExecutorService executorService, CrashlyticsAppQualitySessionsSubscriber crashlyticsAppQualitySessionsSubscriber, RemoteConfigDeferredProxy remoteConfigDeferredProxy) {
this.app = firebaseApp;
this.dataCollectionArbiter = dataCollectionArbiter;
this.context = firebaseApp.getApplicationContext();
this.idManager = idManager;
this.nativeComponent = crashlyticsNativeComponent;
this.breadcrumbSource = breadcrumbSource;
this.analyticsEventLogger = analyticsEventLogger;
this.crashHandlerExecutor = executorService;
this.fileStore = fileStore;
this.backgroundWorker = new CrashlyticsBackgroundWorker(executorService);
this.sessionsSubscriber = crashlyticsAppQualitySessionsSubscriber;
this.remoteConfigDeferredProxy = remoteConfigDeferredProxy;
}
private void checkForPreviousCrash() {
try {
this.didCrashOnPreviousExecution = Boolean.TRUE.equals((Boolean) Utils.awaitEvenIfOnMainThread(this.backgroundWorker.submit(new Callable<Boolean>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsCore.4
/* JADX WARN: Can't rename method to resolve collision */
@Override // java.util.concurrent.Callable
public Boolean call() throws Exception {
return Boolean.valueOf(CrashlyticsCore.this.controller.didCrashOnPreviousExecution());
}
})));
} catch (Exception unused) {
this.didCrashOnPreviousExecution = false;
}
}
/* JADX INFO: Access modifiers changed from: private */
public Task<Void> doBackgroundInitialization(SettingsProvider settingsProvider) {
markInitializationStarted();
try {
this.breadcrumbSource.registerBreadcrumbHandler(new BreadcrumbHandler() { // from class: com.google.firebase.crashlytics.internal.common.c
@Override // com.google.firebase.crashlytics.internal.breadcrumbs.BreadcrumbHandler
public final void handleBreadcrumb(String str) {
CrashlyticsCore.this.log(str);
}
});
this.controller.saveVersionControlInfo();
if (!settingsProvider.getSettingsSync().featureFlagData.collectReports) {
Logger.getLogger().d("Collection of crash reports disabled in Crashlytics settings.");
return Tasks.forException(new RuntimeException("Collection of crash reports disabled in Crashlytics settings."));
}
if (!this.controller.finalizeSessions(settingsProvider)) {
Logger.getLogger().w("Previous sessions could not be finalized.");
}
return this.controller.submitAllReports(settingsProvider.getSettingsAsync());
} catch (Exception e4) {
Logger.getLogger().e("Crashlytics encountered a problem during asynchronous initialization.", e4);
return Tasks.forException(e4);
} finally {
markInitializationComplete();
}
}
private void finishInitSynchronously(final SettingsProvider settingsProvider) {
Future<?> submit = this.crashHandlerExecutor.submit(new Runnable() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsCore.2
@Override // java.lang.Runnable
public void run() {
CrashlyticsCore.this.doBackgroundInitialization(settingsProvider);
}
});
Logger.getLogger().d("Crashlytics detected incomplete initialization on previous app launch. Will initialize synchronously.");
try {
submit.get(3L, TimeUnit.SECONDS);
} catch (InterruptedException e4) {
Logger.getLogger().e("Crashlytics was interrupted during initialization.", e4);
} catch (ExecutionException e5) {
Logger.getLogger().e("Crashlytics encountered a problem during initialization.", e5);
} catch (TimeoutException e6) {
Logger.getLogger().e("Crashlytics timed out during initialization.", e6);
}
}
public static String getVersion() {
return BuildConfig.VERSION_NAME;
}
public static boolean isBuildIdValid(String str, boolean z3) {
if (!z3) {
Logger.getLogger().v("Configured not to require a build ID.");
return CRASHLYTICS_REQUIRE_BUILD_ID_DEFAULT;
}
if (!TextUtils.isEmpty(str)) {
return CRASHLYTICS_REQUIRE_BUILD_ID_DEFAULT;
}
Log.e(Logger.TAG, ".");
Log.e(Logger.TAG, ". | | ");
Log.e(Logger.TAG, ". | |");
Log.e(Logger.TAG, ". | |");
Log.e(Logger.TAG, ". \\ | | /");
Log.e(Logger.TAG, ". \\ /");
Log.e(Logger.TAG, ". \\ /");
Log.e(Logger.TAG, ". \\/");
Log.e(Logger.TAG, ".");
Log.e(Logger.TAG, MISSING_BUILD_ID_MSG);
Log.e(Logger.TAG, ".");
Log.e(Logger.TAG, ". /\\");
Log.e(Logger.TAG, ". / \\");
Log.e(Logger.TAG, ". / \\");
Log.e(Logger.TAG, ". / | | \\");
Log.e(Logger.TAG, ". | |");
Log.e(Logger.TAG, ". | |");
Log.e(Logger.TAG, ". | |");
Log.e(Logger.TAG, ".");
return false;
}
public Task<Boolean> checkForUnsentReports() {
return this.controller.checkForUnsentReports();
}
public Task<Void> deleteUnsentReports() {
return this.controller.deleteUnsentReports();
}
public boolean didCrashOnPreviousExecution() {
return this.didCrashOnPreviousExecution;
}
public boolean didPreviousInitializationFail() {
return this.initializationMarker.isPresent();
}
public Task<Void> doBackgroundInitializationAsync(final SettingsProvider settingsProvider) {
return Utils.callTask(this.crashHandlerExecutor, new Callable<Task<Void>>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsCore.1
/* JADX WARN: Can't rename method to resolve collision */
@Override // java.util.concurrent.Callable
public Task<Void> call() throws Exception {
return CrashlyticsCore.this.doBackgroundInitialization(settingsProvider);
}
});
}
public CrashlyticsController getController() {
return this.controller;
}
public void log(String str) {
this.controller.writeToLog(System.currentTimeMillis() - this.startTime, str);
}
public void logException(Throwable th) {
this.controller.writeNonFatalException(Thread.currentThread(), th);
}
public void logFatalException(Throwable th) {
Logger.getLogger().d("Recorded on-demand fatal events: " + this.onDemandCounter.getRecordedOnDemandExceptions());
Logger.getLogger().d("Dropped on-demand fatal events: " + this.onDemandCounter.getDroppedOnDemandExceptions());
this.controller.setInternalKey(ON_DEMAND_RECORDED_KEY, Integer.toString(this.onDemandCounter.getRecordedOnDemandExceptions()));
this.controller.setInternalKey(ON_DEMAND_DROPPED_KEY, Integer.toString(this.onDemandCounter.getDroppedOnDemandExceptions()));
this.controller.logFatalException(Thread.currentThread(), th);
}
public void markInitializationComplete() {
this.backgroundWorker.submit(new Callable<Boolean>() { // from class: com.google.firebase.crashlytics.internal.common.CrashlyticsCore.3
/* JADX WARN: Can't rename method to resolve collision */
@Override // java.util.concurrent.Callable
public Boolean call() throws Exception {
try {
boolean remove = CrashlyticsCore.this.initializationMarker.remove();
if (!remove) {
Logger.getLogger().w("Initialization marker file was not properly removed.");
}
return Boolean.valueOf(remove);
} catch (Exception e4) {
Logger.getLogger().e("Problem encountered deleting Crashlytics initialization marker.", e4);
return Boolean.FALSE;
}
}
});
}
public void markInitializationStarted() {
this.backgroundWorker.checkRunningOnThread();
this.initializationMarker.create();
Logger.getLogger().v("Initialization marker file was created.");
}
public boolean onPreExecute(AppData appData, SettingsProvider settingsProvider) {
if (!isBuildIdValid(appData.buildId, CommonUtils.getBooleanResourceValue(this.context, CRASHLYTICS_REQUIRE_BUILD_ID, CRASHLYTICS_REQUIRE_BUILD_ID_DEFAULT))) {
throw new IllegalStateException(MISSING_BUILD_ID_MSG);
}
String clsuuid = new CLSUUID(this.idManager).toString();
try {
this.crashMarker = new CrashlyticsFileMarker(CRASH_MARKER_FILE_NAME, this.fileStore);
this.initializationMarker = new CrashlyticsFileMarker(INITIALIZATION_MARKER_FILE_NAME, this.fileStore);
UserMetadata userMetadata = new UserMetadata(clsuuid, this.fileStore, this.backgroundWorker);
LogFileManager logFileManager = new LogFileManager(this.fileStore);
MiddleOutFallbackStrategy middleOutFallbackStrategy = new MiddleOutFallbackStrategy(1024, new RemoveRepeatsStrategy(10));
this.remoteConfigDeferredProxy.setupListener(userMetadata);
this.controller = new CrashlyticsController(this.context, this.backgroundWorker, this.idManager, this.dataCollectionArbiter, this.fileStore, this.crashMarker, appData, userMetadata, logFileManager, SessionReportingCoordinator.create(this.context, this.idManager, this.fileStore, appData, logFileManager, userMetadata, middleOutFallbackStrategy, settingsProvider, this.onDemandCounter, this.sessionsSubscriber), this.nativeComponent, this.analyticsEventLogger, this.sessionsSubscriber);
boolean didPreviousInitializationFail = didPreviousInitializationFail();
checkForPreviousCrash();
this.controller.enableExceptionHandling(clsuuid, Thread.getDefaultUncaughtExceptionHandler(), settingsProvider);
if (!didPreviousInitializationFail || !CommonUtils.canTryConnection(this.context)) {
Logger.getLogger().d("Successfully configured exception handler.");
return CRASHLYTICS_REQUIRE_BUILD_ID_DEFAULT;
}
Logger.getLogger().d("Crashlytics did not finish previous background initialization. Initializing synchronously.");
finishInitSynchronously(settingsProvider);
return false;
} catch (Exception e4) {
Logger.getLogger().e("Crashlytics was not started due to an exception during initialization", e4);
this.controller = null;
return false;
}
}
public Task<Void> sendUnsentReports() {
return this.controller.sendUnsentReports();
}
public void setCrashlyticsCollectionEnabled(Boolean bool) {
this.dataCollectionArbiter.setCrashlyticsDataCollectionEnabled(bool);
}
public void setCustomKey(String str, String str2) {
this.controller.setCustomKey(str, str2);
}
public void setCustomKeys(Map<String, String> map) {
this.controller.setCustomKeys(map);
}
public void setInternalKey(String str, String str2) {
this.controller.setInternalKey(str, str2);
}
public void setUserId(String str) {
this.controller.setUserId(str);
}
}

View File

@@ -0,0 +1,39 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.persistence.FileStore;
import java.io.File;
import java.io.IOException;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public class CrashlyticsFileMarker {
private final FileStore fileStore;
private final String markerName;
public CrashlyticsFileMarker(String str, FileStore fileStore) {
this.markerName = str;
this.fileStore = fileStore;
}
private File getMarkerFile() {
return this.fileStore.getCommonFile(this.markerName);
}
public boolean create() {
try {
return getMarkerFile().createNewFile();
} catch (IOException e4) {
Logger.getLogger().e("Error creating marker: " + this.markerName, e4);
return false;
}
}
public boolean isPresent() {
return getMarkerFile().exists();
}
public boolean remove() {
return getMarkerFile().delete();
}
}

View File

@@ -0,0 +1,12 @@
package com.google.firebase.crashlytics.internal.common;
/* loaded from: classes3.dex */
interface CrashlyticsLifecycleEvents {
void onBeginSession(String str, long j4);
void onCustomKey(String str, String str2);
void onLog(long j4, String str);
void onUserId(String str);
}

View File

@@ -0,0 +1,242 @@
package com.google.firebase.crashlytics.internal.common;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import com.google.firebase.crashlytics.BuildConfig;
import com.google.firebase.crashlytics.internal.ProcessDetailsProvider;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import com.google.firebase.crashlytics.internal.settings.SettingsProvider;
import com.google.firebase.crashlytics.internal.stacktrace.StackTraceTrimmingStrategy;
import com.google.firebase.crashlytics.internal.stacktrace.TrimmedThrowableData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/* loaded from: classes3.dex */
public class CrashlyticsReportDataCapture {
private static final Map<String, Integer> ARCHITECTURES_BY_NAME;
static final String GENERATOR;
static final int GENERATOR_TYPE = 3;
static final int REPORT_ANDROID_PLATFORM = 4;
static final int SESSION_ANDROID_PLATFORM = 3;
static final String SIGNAL_DEFAULT = "0";
private final AppData appData;
private final Context context;
private final IdManager idManager;
private final ProcessDetailsProvider processDetailsProvider = ProcessDetailsProvider.INSTANCE;
private final SettingsProvider settingsProvider;
private final StackTraceTrimmingStrategy stackTraceTrimmingStrategy;
static {
HashMap hashMap = new HashMap();
ARCHITECTURES_BY_NAME = hashMap;
hashMap.put("armeabi", 5);
hashMap.put("armeabi-v7a", 6);
hashMap.put("arm64-v8a", 9);
hashMap.put("x86", 0);
hashMap.put("x86_64", 1);
Locale locale = Locale.US;
GENERATOR = "Crashlytics Android SDK/18.6.0";
}
public CrashlyticsReportDataCapture(Context context, IdManager idManager, AppData appData, StackTraceTrimmingStrategy stackTraceTrimmingStrategy, SettingsProvider settingsProvider) {
this.context = context;
this.idManager = idManager;
this.appData = appData;
this.stackTraceTrimmingStrategy = stackTraceTrimmingStrategy;
this.settingsProvider = settingsProvider;
}
private CrashlyticsReport.ApplicationExitInfo addBuildIdInfo(CrashlyticsReport.ApplicationExitInfo applicationExitInfo) {
List<CrashlyticsReport.ApplicationExitInfo.BuildIdMappingForArch> list;
if (!this.settingsProvider.getSettingsSync().featureFlagData.collectBuildIds || this.appData.buildIdInfoList.size() <= 0) {
list = null;
} else {
ArrayList arrayList = new ArrayList();
for (BuildIdInfo buildIdInfo : this.appData.buildIdInfoList) {
arrayList.add(CrashlyticsReport.ApplicationExitInfo.BuildIdMappingForArch.builder().setLibraryName(buildIdInfo.getLibraryName()).setArch(buildIdInfo.getArch()).setBuildId(buildIdInfo.getBuildId()).build());
}
list = Collections.unmodifiableList(arrayList);
}
return CrashlyticsReport.ApplicationExitInfo.builder().setImportance(applicationExitInfo.getImportance()).setProcessName(applicationExitInfo.getProcessName()).setReasonCode(applicationExitInfo.getReasonCode()).setTimestamp(applicationExitInfo.getTimestamp()).setPid(applicationExitInfo.getPid()).setPss(applicationExitInfo.getPss()).setRss(applicationExitInfo.getRss()).setTraceFile(applicationExitInfo.getTraceFile()).setBuildIdMappingForArch(list).build();
}
private CrashlyticsReport.Builder buildReportData() {
return CrashlyticsReport.builder().setSdkVersion(BuildConfig.VERSION_NAME).setGmpAppId(this.appData.googleAppId).setInstallationUuid(this.idManager.getInstallIds().getCrashlyticsInstallId()).setFirebaseInstallationId(this.idManager.getInstallIds().getFirebaseInstallationId()).setBuildVersion(this.appData.versionCode).setDisplayVersion(this.appData.versionName).setPlatform(4);
}
private static long ensureNonNegative(long j4) {
if (j4 > 0) {
return j4;
}
return 0L;
}
private static int getDeviceArchitecture() {
Integer num;
String str = Build.CPU_ABI;
if (TextUtils.isEmpty(str) || (num = ARCHITECTURES_BY_NAME.get(str.toLowerCase(Locale.US))) == null) {
return 7;
}
return num.intValue();
}
private CrashlyticsReport.Session.Event.Application.Execution.BinaryImage populateBinaryImageData() {
return CrashlyticsReport.Session.Event.Application.Execution.BinaryImage.builder().setBaseAddress(0L).setSize(0L).setName(this.appData.packageName).setUuid(this.appData.buildId).build();
}
private List<CrashlyticsReport.Session.Event.Application.Execution.BinaryImage> populateBinaryImagesList() {
return Collections.singletonList(populateBinaryImageData());
}
private CrashlyticsReport.Session.Event.Application populateEventApplicationData(int i, TrimmedThrowableData trimmedThrowableData, Thread thread, int i4, int i5, boolean z3) {
Boolean bool;
CrashlyticsReport.Session.Event.Application.ProcessDetails currentProcessDetails = this.processDetailsProvider.getCurrentProcessDetails(this.context);
if (currentProcessDetails.getImportance() > 0) {
bool = Boolean.valueOf(currentProcessDetails.getImportance() != 100);
} else {
bool = null;
}
return CrashlyticsReport.Session.Event.Application.builder().setBackground(bool).setCurrentProcessDetails(currentProcessDetails).setAppProcessDetails(this.processDetailsProvider.getAppProcessDetails(this.context)).setUiOrientation(i).setExecution(populateExecutionData(trimmedThrowableData, thread, i4, i5, z3)).build();
}
private CrashlyticsReport.Session.Event.Device populateEventDeviceData(int i) {
BatteryState batteryState = BatteryState.get(this.context);
Float batteryLevel = batteryState.getBatteryLevel();
Double valueOf = batteryLevel != null ? Double.valueOf(batteryLevel.doubleValue()) : null;
int batteryVelocity = batteryState.getBatteryVelocity();
boolean proximitySensorEnabled = CommonUtils.getProximitySensorEnabled(this.context);
return CrashlyticsReport.Session.Event.Device.builder().setBatteryLevel(valueOf).setBatteryVelocity(batteryVelocity).setProximityOn(proximitySensorEnabled).setOrientation(i).setRamUsed(ensureNonNegative(CommonUtils.calculateTotalRamInBytes(this.context) - CommonUtils.calculateFreeRamInBytes(this.context))).setDiskUsed(CommonUtils.calculateUsedDiskSpaceInBytes(Environment.getDataDirectory().getPath())).build();
}
private CrashlyticsReport.Session.Event.Application.Execution.Exception populateExceptionData(TrimmedThrowableData trimmedThrowableData, int i, int i4) {
return populateExceptionData(trimmedThrowableData, i, i4, 0);
}
private CrashlyticsReport.Session.Event.Application.Execution populateExecutionData(TrimmedThrowableData trimmedThrowableData, Thread thread, int i, int i4, boolean z3) {
return CrashlyticsReport.Session.Event.Application.Execution.builder().setThreads(populateThreadsList(trimmedThrowableData, thread, i, z3)).setException(populateExceptionData(trimmedThrowableData, i, i4)).setSignal(populateSignalData()).setBinaries(populateBinaryImagesList()).build();
}
private CrashlyticsReport.Session.Event.Application.Execution.Thread.Frame populateFrameData(StackTraceElement stackTraceElement, CrashlyticsReport.Session.Event.Application.Execution.Thread.Frame.Builder builder) {
long j4 = 0;
long max = stackTraceElement.isNativeMethod() ? Math.max(stackTraceElement.getLineNumber(), 0L) : 0L;
String str = stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName();
String fileName = stackTraceElement.getFileName();
if (!stackTraceElement.isNativeMethod() && stackTraceElement.getLineNumber() > 0) {
j4 = stackTraceElement.getLineNumber();
}
return builder.setPc(max).setSymbol(str).setFile(fileName).setOffset(j4).build();
}
private List<CrashlyticsReport.Session.Event.Application.Execution.Thread.Frame> populateFramesList(StackTraceElement[] stackTraceElementArr, int i) {
ArrayList arrayList = new ArrayList();
for (StackTraceElement stackTraceElement : stackTraceElementArr) {
arrayList.add(populateFrameData(stackTraceElement, CrashlyticsReport.Session.Event.Application.Execution.Thread.Frame.builder().setImportance(i)));
}
return Collections.unmodifiableList(arrayList);
}
private CrashlyticsReport.Session.Application populateSessionApplicationData() {
return CrashlyticsReport.Session.Application.builder().setIdentifier(this.idManager.getAppIdentifier()).setVersion(this.appData.versionCode).setDisplayVersion(this.appData.versionName).setInstallationUuid(this.idManager.getInstallIds().getCrashlyticsInstallId()).setDevelopmentPlatform(this.appData.developmentPlatformProvider.getDevelopmentPlatform()).setDevelopmentPlatformVersion(this.appData.developmentPlatformProvider.getDevelopmentPlatformVersion()).build();
}
private CrashlyticsReport.Session populateSessionData(String str, long j4) {
return CrashlyticsReport.Session.builder().setStartedAt(j4).setIdentifier(str).setGenerator(GENERATOR).setApp(populateSessionApplicationData()).setOs(populateSessionOperatingSystemData()).setDevice(populateSessionDeviceData()).setGeneratorType(3).build();
}
private CrashlyticsReport.Session.Device populateSessionDeviceData() {
StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
int deviceArchitecture = getDeviceArchitecture();
int availableProcessors = Runtime.getRuntime().availableProcessors();
long calculateTotalRamInBytes = CommonUtils.calculateTotalRamInBytes(this.context);
long blockCount = statFs.getBlockCount() * statFs.getBlockSize();
boolean isEmulator = CommonUtils.isEmulator();
int deviceState = CommonUtils.getDeviceState();
return CrashlyticsReport.Session.Device.builder().setArch(deviceArchitecture).setModel(Build.MODEL).setCores(availableProcessors).setRam(calculateTotalRamInBytes).setDiskSpace(blockCount).setSimulator(isEmulator).setState(deviceState).setManufacturer(Build.MANUFACTURER).setModelClass(Build.PRODUCT).build();
}
private CrashlyticsReport.Session.OperatingSystem populateSessionOperatingSystemData() {
return CrashlyticsReport.Session.OperatingSystem.builder().setPlatform(3).setVersion(Build.VERSION.RELEASE).setBuildVersion(Build.VERSION.CODENAME).setJailbroken(CommonUtils.isRooted()).build();
}
private CrashlyticsReport.Session.Event.Application.Execution.Signal populateSignalData() {
return CrashlyticsReport.Session.Event.Application.Execution.Signal.builder().setName("0").setCode("0").setAddress(0L).build();
}
private CrashlyticsReport.Session.Event.Application.Execution.Thread populateThreadData(Thread thread, StackTraceElement[] stackTraceElementArr) {
return populateThreadData(thread, stackTraceElementArr, 0);
}
private List<CrashlyticsReport.Session.Event.Application.Execution.Thread> populateThreadsList(TrimmedThrowableData trimmedThrowableData, Thread thread, int i, boolean z3) {
ArrayList arrayList = new ArrayList();
arrayList.add(populateThreadData(thread, trimmedThrowableData.stacktrace, i));
if (z3) {
for (Map.Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) {
Thread key = entry.getKey();
if (!key.equals(thread)) {
arrayList.add(populateThreadData(key, this.stackTraceTrimmingStrategy.getTrimmedStackTrace(entry.getValue())));
}
}
}
return Collections.unmodifiableList(arrayList);
}
private CrashlyticsReport.Session.Event.Application.ProcessDetails processDetailsFromApplicationExitInfo(CrashlyticsReport.ApplicationExitInfo applicationExitInfo) {
return this.processDetailsProvider.buildProcessDetails(applicationExitInfo.getProcessName(), applicationExitInfo.getPid(), applicationExitInfo.getImportance());
}
public CrashlyticsReport.Session.Event captureAnrEventData(CrashlyticsReport.ApplicationExitInfo applicationExitInfo) {
int i = this.context.getResources().getConfiguration().orientation;
return CrashlyticsReport.Session.Event.builder().setType("anr").setTimestamp(applicationExitInfo.getTimestamp()).setApp(populateEventApplicationData(i, addBuildIdInfo(applicationExitInfo))).setDevice(populateEventDeviceData(i)).build();
}
public CrashlyticsReport.Session.Event captureEventData(Throwable th, Thread thread, String str, long j4, int i, int i4, boolean z3) {
int i5 = this.context.getResources().getConfiguration().orientation;
return CrashlyticsReport.Session.Event.builder().setType(str).setTimestamp(j4).setApp(populateEventApplicationData(i5, TrimmedThrowableData.makeTrimmedThrowableData(th, this.stackTraceTrimmingStrategy), thread, i, i4, z3)).setDevice(populateEventDeviceData(i5)).build();
}
public CrashlyticsReport captureReportData(String str, long j4) {
return buildReportData().setSession(populateSessionData(str, j4)).build();
}
private CrashlyticsReport.Session.Event.Application.Execution.Exception populateExceptionData(TrimmedThrowableData trimmedThrowableData, int i, int i4, int i5) {
String str = trimmedThrowableData.className;
String str2 = trimmedThrowableData.localizedMessage;
StackTraceElement[] stackTraceElementArr = trimmedThrowableData.stacktrace;
int i6 = 0;
if (stackTraceElementArr == null) {
stackTraceElementArr = new StackTraceElement[0];
}
TrimmedThrowableData trimmedThrowableData2 = trimmedThrowableData.cause;
if (i5 >= i4) {
TrimmedThrowableData trimmedThrowableData3 = trimmedThrowableData2;
while (trimmedThrowableData3 != null) {
trimmedThrowableData3 = trimmedThrowableData3.cause;
i6++;
}
}
CrashlyticsReport.Session.Event.Application.Execution.Exception.Builder overflowCount = CrashlyticsReport.Session.Event.Application.Execution.Exception.builder().setType(str).setReason(str2).setFrames(populateFramesList(stackTraceElementArr, i)).setOverflowCount(i6);
if (trimmedThrowableData2 != null && i6 == 0) {
overflowCount.setCausedBy(populateExceptionData(trimmedThrowableData2, i, i4, i5 + 1));
}
return overflowCount.build();
}
private CrashlyticsReport.Session.Event.Application.Execution.Thread populateThreadData(Thread thread, StackTraceElement[] stackTraceElementArr, int i) {
return CrashlyticsReport.Session.Event.Application.Execution.Thread.builder().setName(thread.getName()).setImportance(i).setFrames(populateFramesList(stackTraceElementArr, i)).build();
}
private CrashlyticsReport.Session.Event.Application.Execution populateExecutionData(CrashlyticsReport.ApplicationExitInfo applicationExitInfo) {
return CrashlyticsReport.Session.Event.Application.Execution.builder().setAppExitInfo(applicationExitInfo).setSignal(populateSignalData()).setBinaries(populateBinaryImagesList()).build();
}
private CrashlyticsReport.Session.Event.Application populateEventApplicationData(int i, CrashlyticsReport.ApplicationExitInfo applicationExitInfo) {
return CrashlyticsReport.Session.Event.Application.builder().setBackground(Boolean.valueOf(applicationExitInfo.getImportance() != 100)).setCurrentProcessDetails(processDetailsFromApplicationExitInfo(applicationExitInfo)).setUiOrientation(i).setExecution(populateExecutionData(applicationExitInfo)).build();
}
}

View File

@@ -0,0 +1,19 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.auto.value.AutoValue;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import java.io.File;
@AutoValue
/* loaded from: classes3.dex */
public abstract class CrashlyticsReportWithSessionId {
public static CrashlyticsReportWithSessionId create(CrashlyticsReport crashlyticsReport, String str, File file) {
return new AutoValue_CrashlyticsReportWithSessionId(crashlyticsReport, str, file);
}
public abstract CrashlyticsReport getReport();
public abstract File getReportFile();
public abstract String getSessionId();
}

View File

@@ -0,0 +1,76 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.CrashlyticsNativeComponent;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.settings.SettingsProvider;
import java.lang.Thread;
import java.util.concurrent.atomic.AtomicBoolean;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public class CrashlyticsUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private final CrashListener crashListener;
private final Thread.UncaughtExceptionHandler defaultHandler;
private final AtomicBoolean isHandlingException = new AtomicBoolean(false);
private final CrashlyticsNativeComponent nativeComponent;
private final SettingsProvider settingsProvider;
/* loaded from: classes3.dex */
public interface CrashListener {
void onUncaughtException(SettingsProvider settingsProvider, Thread thread, Throwable th);
}
public CrashlyticsUncaughtExceptionHandler(CrashListener crashListener, SettingsProvider settingsProvider, Thread.UncaughtExceptionHandler uncaughtExceptionHandler, CrashlyticsNativeComponent crashlyticsNativeComponent) {
this.crashListener = crashListener;
this.settingsProvider = settingsProvider;
this.defaultHandler = uncaughtExceptionHandler;
this.nativeComponent = crashlyticsNativeComponent;
}
private boolean shouldRecordUncaughtException(Thread thread, Throwable th) {
if (thread == null) {
Logger.getLogger().e("Crashlytics will not record uncaught exception; null thread");
return false;
}
if (th == null) {
Logger.getLogger().e("Crashlytics will not record uncaught exception; null throwable");
return false;
}
if (!this.nativeComponent.hasCrashDataForCurrentSession()) {
return true;
}
Logger.getLogger().d("Crashlytics will not record uncaught exception; native crash exists for session.");
return false;
}
public boolean isHandlingException() {
return this.isHandlingException.get();
}
@Override // java.lang.Thread.UncaughtExceptionHandler
public void uncaughtException(Thread thread, Throwable th) {
this.isHandlingException.set(true);
try {
try {
if (shouldRecordUncaughtException(thread, th)) {
this.crashListener.onUncaughtException(this.settingsProvider, thread, th);
} else {
Logger.getLogger().d("Uncaught exception will not be recorded by Crashlytics.");
}
Logger.getLogger().d("Completed exception processing. Invoking default exception handler.");
this.defaultHandler.uncaughtException(thread, th);
this.isHandlingException.set(false);
} catch (Exception e4) {
Logger.getLogger().e("An error occurred in the uncaught exception handler", e4);
Logger.getLogger().d("Completed exception processing. Invoking default exception handler.");
this.defaultHandler.uncaughtException(thread, th);
this.isHandlingException.set(false);
}
} catch (Throwable th2) {
Logger.getLogger().d("Completed exception processing. Invoking default exception handler.");
this.defaultHandler.uncaughtException(thread, th);
this.isHandlingException.set(false);
throw th2;
}
}
}

View File

@@ -0,0 +1,6 @@
package com.google.firebase.crashlytics.internal.common;
/* loaded from: classes3.dex */
public interface CurrentTimeProvider {
long getCurrentTimeMillis();
}

View File

@@ -0,0 +1,165 @@
package com.google.firebase.crashlytics.internal.common;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.firebase.FirebaseApp;
import com.google.firebase.crashlytics.internal.Logger;
import java.util.concurrent.Executor;
/* loaded from: classes3.dex */
public class DataCollectionArbiter {
private static final String FIREBASE_CRASHLYTICS_COLLECTION_ENABLED = "firebase_crashlytics_collection_enabled";
private Boolean crashlyticsDataCollectionEnabled;
TaskCompletionSource<Void> dataCollectionEnabledTask;
private final TaskCompletionSource<Void> dataCollectionExplicitlyApproved;
private final FirebaseApp firebaseApp;
private boolean setInManifest;
private final SharedPreferences sharedPreferences;
private final Object taskLock;
boolean taskResolved;
public DataCollectionArbiter(FirebaseApp firebaseApp) {
Object obj = new Object();
this.taskLock = obj;
this.dataCollectionEnabledTask = new TaskCompletionSource<>();
this.taskResolved = false;
this.setInManifest = false;
this.dataCollectionExplicitlyApproved = new TaskCompletionSource<>();
Context applicationContext = firebaseApp.getApplicationContext();
this.firebaseApp = firebaseApp;
this.sharedPreferences = CommonUtils.getSharedPrefs(applicationContext);
Boolean dataCollectionValueFromSharedPreferences = getDataCollectionValueFromSharedPreferences();
this.crashlyticsDataCollectionEnabled = dataCollectionValueFromSharedPreferences == null ? getDataCollectionValueFromManifest(applicationContext) : dataCollectionValueFromSharedPreferences;
synchronized (obj) {
try {
if (isAutomaticDataCollectionEnabled()) {
this.dataCollectionEnabledTask.trySetResult(null);
this.taskResolved = true;
}
} catch (Throwable th) {
throw th;
}
}
}
private Boolean getDataCollectionValueFromManifest(Context context) {
Boolean readCrashlyticsDataCollectionEnabledFromManifest = readCrashlyticsDataCollectionEnabledFromManifest(context);
if (readCrashlyticsDataCollectionEnabledFromManifest == null) {
this.setInManifest = false;
return null;
}
this.setInManifest = true;
return Boolean.valueOf(Boolean.TRUE.equals(readCrashlyticsDataCollectionEnabledFromManifest));
}
private Boolean getDataCollectionValueFromSharedPreferences() {
if (!this.sharedPreferences.contains(FIREBASE_CRASHLYTICS_COLLECTION_ENABLED)) {
return null;
}
this.setInManifest = false;
return Boolean.valueOf(this.sharedPreferences.getBoolean(FIREBASE_CRASHLYTICS_COLLECTION_ENABLED, true));
}
private boolean isFirebaseDataCollectionDefaultEnabled() {
try {
return this.firebaseApp.isDataCollectionDefaultEnabled();
} catch (IllegalStateException unused) {
return false;
}
}
private void logDataCollectionState(boolean z3) {
String str = z3 ? "ENABLED" : "DISABLED";
String str2 = this.crashlyticsDataCollectionEnabled == null ? "global Firebase setting" : this.setInManifest ? "firebase_crashlytics_collection_enabled manifest flag" : "API";
Logger.getLogger().d("Crashlytics automatic data collection " + str + " by " + str2 + ".");
}
private static Boolean readCrashlyticsDataCollectionEnabledFromManifest(Context context) {
ApplicationInfo applicationInfo;
Bundle bundle;
try {
PackageManager packageManager = context.getPackageManager();
if (packageManager == null || (applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 128)) == null || (bundle = applicationInfo.metaData) == null || !bundle.containsKey(FIREBASE_CRASHLYTICS_COLLECTION_ENABLED)) {
return null;
}
return Boolean.valueOf(applicationInfo.metaData.getBoolean(FIREBASE_CRASHLYTICS_COLLECTION_ENABLED));
} catch (PackageManager.NameNotFoundException e4) {
Logger.getLogger().e("Could not read data collection permission from manifest", e4);
return null;
}
}
@SuppressLint({"ApplySharedPref"})
private static void storeDataCollectionValueInSharedPreferences(SharedPreferences sharedPreferences, Boolean bool) {
SharedPreferences.Editor edit = sharedPreferences.edit();
if (bool != null) {
edit.putBoolean(FIREBASE_CRASHLYTICS_COLLECTION_ENABLED, bool.booleanValue());
} else {
edit.remove(FIREBASE_CRASHLYTICS_COLLECTION_ENABLED);
}
edit.apply();
}
public void grantDataCollectionPermission(boolean z3) {
if (!z3) {
throw new IllegalStateException("An invalid data collection token was used.");
}
this.dataCollectionExplicitlyApproved.trySetResult(null);
}
public synchronized boolean isAutomaticDataCollectionEnabled() {
boolean booleanValue;
try {
Boolean bool = this.crashlyticsDataCollectionEnabled;
booleanValue = bool != null ? bool.booleanValue() : isFirebaseDataCollectionDefaultEnabled();
logDataCollectionState(booleanValue);
} catch (Throwable th) {
throw th;
}
return booleanValue;
}
public synchronized void setCrashlyticsDataCollectionEnabled(Boolean bool) {
if (bool != null) {
try {
this.setInManifest = false;
} catch (Throwable th) {
throw th;
}
}
this.crashlyticsDataCollectionEnabled = bool != null ? bool : getDataCollectionValueFromManifest(this.firebaseApp.getApplicationContext());
storeDataCollectionValueInSharedPreferences(this.sharedPreferences, bool);
synchronized (this.taskLock) {
try {
if (isAutomaticDataCollectionEnabled()) {
if (!this.taskResolved) {
this.dataCollectionEnabledTask.trySetResult(null);
this.taskResolved = true;
}
} else if (this.taskResolved) {
this.dataCollectionEnabledTask = new TaskCompletionSource<>();
this.taskResolved = false;
}
} finally {
}
}
}
public Task<Void> waitForAutomaticDataCollectionEnabled() {
Task<Void> task;
synchronized (this.taskLock) {
task = this.dataCollectionEnabledTask.getTask();
}
return task;
}
public Task<Void> waitForDataCollectionPermission(Executor executor) {
return Utils.race(executor, this.dataCollectionExplicitlyApproved.getTask(), waitForAutomaticDataCollectionEnabled());
}
}

View File

@@ -0,0 +1,28 @@
package com.google.firebase.crashlytics.internal.common;
/* loaded from: classes3.dex */
public enum DeliveryMechanism {
DEVELOPER(1),
USER_SIDELOAD(2),
TEST_DISTRIBUTION(3),
APP_STORE(4);
private final int id;
DeliveryMechanism(int i) {
this.id = i;
}
public static DeliveryMechanism determineFrom(String str) {
return str != null ? APP_STORE : DEVELOPER;
}
public int getId() {
return this.id;
}
@Override // java.lang.Enum
public String toString() {
return Integer.toString(this.id);
}
}

View File

@@ -0,0 +1,84 @@
package com.google.firebase.crashlytics.internal.common;
import C.w;
import android.annotation.SuppressLint;
import com.google.firebase.crashlytics.internal.Logger;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/* loaded from: classes3.dex */
public final class ExecutorUtils {
private static final long DEFAULT_TERMINATION_TIMEOUT = 2;
private ExecutorUtils() {
}
private static void addDelayedShutdownHook(String str, ExecutorService executorService) {
addDelayedShutdownHook(str, executorService, DEFAULT_TERMINATION_TIMEOUT, TimeUnit.SECONDS);
}
public static ExecutorService buildSingleThreadExecutorService(String str) {
ExecutorService newSingleThreadExecutor = newSingleThreadExecutor(getNamedThreadFactory(str), new ThreadPoolExecutor.DiscardPolicy());
addDelayedShutdownHook(str, newSingleThreadExecutor);
return newSingleThreadExecutor;
}
public static ScheduledExecutorService buildSingleThreadScheduledExecutorService(String str) {
ScheduledExecutorService newSingleThreadScheduledExecutor = Executors.newSingleThreadScheduledExecutor(getNamedThreadFactory(str));
addDelayedShutdownHook(str, newSingleThreadScheduledExecutor);
return newSingleThreadScheduledExecutor;
}
public static ThreadFactory getNamedThreadFactory(final String str) {
final AtomicLong atomicLong = new AtomicLong(1L);
return new ThreadFactory() { // from class: com.google.firebase.crashlytics.internal.common.ExecutorUtils.1
@Override // java.util.concurrent.ThreadFactory
public Thread newThread(final Runnable runnable) {
Thread newThread = Executors.defaultThreadFactory().newThread(new BackgroundPriorityRunnable() { // from class: com.google.firebase.crashlytics.internal.common.ExecutorUtils.1.1
@Override // com.google.firebase.crashlytics.internal.common.BackgroundPriorityRunnable
public void onRun() {
runnable.run();
}
});
newThread.setName(str + atomicLong.getAndIncrement());
return newThread;
}
};
}
@SuppressLint({"ThreadPoolCreation"})
private static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
return Executors.unconfigurableExecutorService(new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), threadFactory, rejectedExecutionHandler));
}
@SuppressLint({"ThreadPoolCreation"})
private static void addDelayedShutdownHook(final String str, final ExecutorService executorService, final long j4, final TimeUnit timeUnit) {
Runtime.getRuntime().addShutdownHook(new Thread(new BackgroundPriorityRunnable() { // from class: com.google.firebase.crashlytics.internal.common.ExecutorUtils.2
@Override // com.google.firebase.crashlytics.internal.common.BackgroundPriorityRunnable
public void onRun() {
try {
Logger.getLogger().d("Executing shutdown hook for " + str);
executorService.shutdown();
if (executorService.awaitTermination(j4, timeUnit)) {
return;
}
Logger.getLogger().d(str + " did not shut down in the allocated time. Requesting immediate shutdown.");
executorService.shutdownNow();
} catch (InterruptedException unused) {
Logger logger = Logger.getLogger();
Locale locale = Locale.US;
logger.d("Interrupted while waiting for " + str + " to shut down. Requesting immediate shutdown.");
executorService.shutdownNow();
}
}
}, w.z("Crashlytics Shutdown Hook for ", str)));
}
}

View File

@@ -0,0 +1,95 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPOutputStream;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public class FileBackedNativeSessionFile implements NativeSessionFile {
private final String dataTransportFilename;
private final File file;
private final String reportsEndpointFilename;
public FileBackedNativeSessionFile(String str, String str2, File file) {
this.dataTransportFilename = str;
this.reportsEndpointFilename = str2;
this.file = file;
}
private byte[] asGzippedBytes() {
byte[] bArr = new byte[8192];
try {
InputStream stream = getStream();
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
if (stream == null) {
gZIPOutputStream.close();
byteArrayOutputStream.close();
if (stream != null) {
stream.close();
}
return null;
}
while (true) {
try {
int read = stream.read(bArr);
if (read <= 0) {
gZIPOutputStream.finish();
byte[] byteArray = byteArrayOutputStream.toByteArray();
gZIPOutputStream.close();
byteArrayOutputStream.close();
stream.close();
return byteArray;
}
gZIPOutputStream.write(bArr, 0, read);
} finally {
}
}
} catch (Throwable th) {
try {
byteArrayOutputStream.close();
} catch (Throwable th2) {
th.addSuppressed(th2);
}
throw th;
}
} finally {
}
} catch (IOException unused) {
return null;
}
}
@Override // com.google.firebase.crashlytics.internal.common.NativeSessionFile
public CrashlyticsReport.FilesPayload.File asFilePayload() {
byte[] asGzippedBytes = asGzippedBytes();
if (asGzippedBytes != null) {
return CrashlyticsReport.FilesPayload.File.builder().setContents(asGzippedBytes).setFilename(this.dataTransportFilename).build();
}
return null;
}
@Override // com.google.firebase.crashlytics.internal.common.NativeSessionFile
public String getReportsEndpointFilename() {
return this.reportsEndpointFilename;
}
@Override // com.google.firebase.crashlytics.internal.common.NativeSessionFile
public InputStream getStream() {
if (this.file.exists() && this.file.isFile()) {
try {
return new FileInputStream(this.file);
} catch (FileNotFoundException unused) {
}
}
return null;
}
}

View File

@@ -0,0 +1,142 @@
package com.google.firebase.crashlytics.internal.common;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.common.InstallIdProvider;
import com.google.firebase.installations.FirebaseInstallationsApi;
import com.google.firebase.sessions.settings.RemoteSettings;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Pattern;
/* loaded from: classes3.dex */
public class IdManager implements InstallIdProvider {
public static final String DEFAULT_VERSION_NAME = "0.0";
static final String PREFKEY_ADVERTISING_ID = "crashlytics.advertising.id";
static final String PREFKEY_FIREBASE_IID = "firebase.installation.id";
static final String PREFKEY_INSTALLATION_UUID = "crashlytics.installation.id";
static final String PREFKEY_LEGACY_INSTALLATION_UUID = "crashlytics.installation.id";
private static final String SYNTHETIC_FID_PREFIX = "SYN_";
private final Context appContext;
private final String appIdentifier;
private final DataCollectionArbiter dataCollectionArbiter;
private final FirebaseInstallationsApi firebaseInstallationsApi;
private InstallIdProvider.InstallIds installIds;
private final InstallerPackageNameProvider installerPackageNameProvider;
private static final Pattern ID_PATTERN = Pattern.compile("[^\\p{Alnum}]");
private static final String FORWARD_SLASH_REGEX = Pattern.quote(RemoteSettings.FORWARD_SLASH_STRING);
public IdManager(Context context, String str, FirebaseInstallationsApi firebaseInstallationsApi, DataCollectionArbiter dataCollectionArbiter) {
if (context == null) {
throw new IllegalArgumentException("appContext must not be null");
}
if (str == null) {
throw new IllegalArgumentException("appIdentifier must not be null");
}
this.appContext = context;
this.appIdentifier = str;
this.firebaseInstallationsApi = firebaseInstallationsApi;
this.dataCollectionArbiter = dataCollectionArbiter;
this.installerPackageNameProvider = new InstallerPackageNameProvider();
}
private synchronized String createAndCacheCrashlyticsInstallId(String str, SharedPreferences sharedPreferences) {
String formatId;
formatId = formatId(UUID.randomUUID().toString());
Logger.getLogger().v("Created new Crashlytics installation ID: " + formatId + " for FID: " + str);
sharedPreferences.edit().putString("crashlytics.installation.id", formatId).putString(PREFKEY_FIREBASE_IID, str).apply();
return formatId;
}
public static String createSyntheticFid() {
return SYNTHETIC_FID_PREFIX + UUID.randomUUID().toString();
}
private static String formatId(String str) {
if (str == null) {
return null;
}
return ID_PATTERN.matcher(str).replaceAll("").toLowerCase(Locale.US);
}
public static boolean isSyntheticFid(String str) {
return str != null && str.startsWith(SYNTHETIC_FID_PREFIX);
}
private String readCachedCrashlyticsInstallId(SharedPreferences sharedPreferences) {
return sharedPreferences.getString("crashlytics.installation.id", null);
}
private String removeForwardSlashesIn(String str) {
return str.replaceAll(FORWARD_SLASH_REGEX, "");
}
private boolean shouldRefresh() {
InstallIdProvider.InstallIds installIds = this.installIds;
if (installIds != null) {
return installIds.getFirebaseInstallationId() == null && this.dataCollectionArbiter.isAutomaticDataCollectionEnabled();
}
return true;
}
public String fetchTrueFid() {
try {
return (String) Utils.awaitEvenIfOnMainThread(this.firebaseInstallationsApi.getId());
} catch (Exception e4) {
Logger.getLogger().w("Failed to retrieve Firebase Installation ID.", e4);
return null;
}
}
public String getAppIdentifier() {
return this.appIdentifier;
}
@Override // com.google.firebase.crashlytics.internal.common.InstallIdProvider
public synchronized InstallIdProvider.InstallIds getInstallIds() {
if (!shouldRefresh()) {
return this.installIds;
}
Logger.getLogger().v("Determining Crashlytics installation ID...");
SharedPreferences sharedPrefs = CommonUtils.getSharedPrefs(this.appContext);
String string = sharedPrefs.getString(PREFKEY_FIREBASE_IID, null);
Logger.getLogger().v("Cached Firebase Installation ID: " + string);
if (this.dataCollectionArbiter.isAutomaticDataCollectionEnabled()) {
String fetchTrueFid = fetchTrueFid();
Logger.getLogger().v("Fetched Firebase Installation ID: " + fetchTrueFid);
if (fetchTrueFid == null) {
fetchTrueFid = string == null ? createSyntheticFid() : string;
}
if (fetchTrueFid.equals(string)) {
this.installIds = InstallIdProvider.InstallIds.create(readCachedCrashlyticsInstallId(sharedPrefs), fetchTrueFid);
} else {
this.installIds = InstallIdProvider.InstallIds.create(createAndCacheCrashlyticsInstallId(fetchTrueFid, sharedPrefs), fetchTrueFid);
}
} else if (isSyntheticFid(string)) {
this.installIds = InstallIdProvider.InstallIds.createWithoutFid(readCachedCrashlyticsInstallId(sharedPrefs));
} else {
this.installIds = InstallIdProvider.InstallIds.createWithoutFid(createAndCacheCrashlyticsInstallId(createSyntheticFid(), sharedPrefs));
}
Logger.getLogger().v("Install IDs: " + this.installIds);
return this.installIds;
}
public String getInstallerPackageName() {
return this.installerPackageNameProvider.getInstallerPackageName(this.appContext);
}
public String getModelName() {
Locale locale = Locale.US;
return removeForwardSlashesIn(Build.MANUFACTURER) + RemoteSettings.FORWARD_SLASH_STRING + removeForwardSlashesIn(Build.MODEL);
}
public String getOsBuildVersionString() {
return removeForwardSlashesIn(Build.VERSION.INCREMENTAL);
}
public String getOsDisplayVersionString() {
return removeForwardSlashesIn(Build.VERSION.RELEASE);
}
}

View File

@@ -0,0 +1,25 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.auto.value.AutoValue;
/* loaded from: classes3.dex */
public interface InstallIdProvider {
@AutoValue
/* loaded from: classes3.dex */
public static abstract class InstallIds {
public static InstallIds create(String str, String str2) {
return new AutoValue_InstallIdProvider_InstallIds(str, str2);
}
public static InstallIds createWithoutFid(String str) {
return create(str, null);
}
public abstract String getCrashlyticsInstallId();
public abstract String getFirebaseInstallationId();
}
InstallIds getInstallIds();
}

View File

@@ -0,0 +1,24 @@
package com.google.firebase.crashlytics.internal.common;
import android.content.Context;
/* loaded from: classes3.dex */
class InstallerPackageNameProvider {
private static final String NO_INSTALLER_PACKAGE_NAME = "";
private String installerPackageName;
private static String loadInstallerPackageName(Context context) {
String installerPackageName = context.getPackageManager().getInstallerPackageName(context.getPackageName());
return installerPackageName == null ? "" : installerPackageName;
}
public synchronized String getInstallerPackageName(Context context) {
try {
if (this.installerPackageName == null) {
this.installerPackageName = loadInstallerPackageName(context);
}
} finally {
}
return "".equals(this.installerPackageName) ? null : this.installerPackageName;
}
}

View File

@@ -0,0 +1,14 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import java.io.InputStream;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public interface NativeSessionFile {
CrashlyticsReport.FilesPayload.File asFilePayload();
String getReportsEndpointFilename();
InputStream getStream();
}

View File

@@ -0,0 +1,58 @@
package com.google.firebase.crashlytics.internal.common;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.GZIPOutputStream;
/* JADX INFO: Access modifiers changed from: package-private */
/* loaded from: classes3.dex */
public class NativeSessionFileGzipper {
private static void gzipInputStream(InputStream inputStream, File file) throws IOException {
if (inputStream == null) {
return;
}
byte[] bArr = new byte[8192];
GZIPOutputStream gZIPOutputStream = null;
try {
GZIPOutputStream gZIPOutputStream2 = new GZIPOutputStream(new FileOutputStream(file));
while (true) {
try {
int read = inputStream.read(bArr);
if (read <= 0) {
gZIPOutputStream2.finish();
CommonUtils.closeQuietly(gZIPOutputStream2);
return;
}
gZIPOutputStream2.write(bArr, 0, read);
} catch (Throwable th) {
th = th;
gZIPOutputStream = gZIPOutputStream2;
CommonUtils.closeQuietly(gZIPOutputStream);
throw th;
}
}
} catch (Throwable th2) {
th = th2;
}
}
public static void processNativeSessions(File file, List<NativeSessionFile> list) {
for (NativeSessionFile nativeSessionFile : list) {
InputStream inputStream = null;
try {
inputStream = nativeSessionFile.getStream();
if (inputStream != null) {
gzipInputStream(inputStream, new File(file, nativeSessionFile.getReportsEndpointFilename()));
}
} catch (IOException unused) {
} catch (Throwable th) {
CommonUtils.closeQuietly(null);
throw th;
}
CommonUtils.closeQuietly(inputStream);
}
}
}

View File

@@ -0,0 +1,29 @@
package com.google.firebase.crashlytics.internal.common;
import java.util.concurrent.atomic.AtomicInteger;
/* loaded from: classes3.dex */
public final class OnDemandCounter {
private final AtomicInteger recordedOnDemandExceptions = new AtomicInteger();
private final AtomicInteger droppedOnDemandExceptions = new AtomicInteger();
public int getDroppedOnDemandExceptions() {
return this.droppedOnDemandExceptions.get();
}
public int getRecordedOnDemandExceptions() {
return this.recordedOnDemandExceptions.get();
}
public void incrementDroppedOnDemandExceptions() {
this.droppedOnDemandExceptions.getAndIncrement();
}
public void incrementRecordedOnDemandExceptions() {
this.recordedOnDemandExceptions.getAndIncrement();
}
public void resetDroppedOnDemandExceptions() {
this.droppedOnDemandExceptions.set(0);
}
}

View File

@@ -0,0 +1,14 @@
package com.google.firebase.crashlytics.internal.common;
/* loaded from: classes3.dex */
public class ResponseParser {
public static final int ResponseActionDiscard = 0;
public static final int ResponseActionRetry = 1;
public static int parse(int i) {
if (i < 200 || i > 299) {
return ((i < 300 || i > 399) && i >= 400 && i <= 499) ? 0 : 1;
}
return 0;
}
}

View File

@@ -0,0 +1,289 @@
package com.google.firebase.crashlytics.internal.common;
import I2.k;
import android.app.ApplicationExitInfo;
import android.content.Context;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.crashlytics.internal.Logger;
import com.google.firebase.crashlytics.internal.metadata.LogFileManager;
import com.google.firebase.crashlytics.internal.metadata.UserMetadata;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import com.google.firebase.crashlytics.internal.persistence.CrashlyticsReportPersistence;
import com.google.firebase.crashlytics.internal.persistence.FileStore;
import com.google.firebase.crashlytics.internal.send.DataTransportCrashlyticsReportSender;
import com.google.firebase.crashlytics.internal.settings.SettingsProvider;
import com.google.firebase.crashlytics.internal.stacktrace.StackTraceTrimmingStrategy;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.concurrent.Executor;
/* loaded from: classes3.dex */
public class SessionReportingCoordinator implements CrashlyticsLifecycleEvents {
private static final int DEFAULT_BUFFER_SIZE = 8192;
private static final int EVENT_THREAD_IMPORTANCE = 4;
private static final String EVENT_TYPE_CRASH = "crash";
private static final String EVENT_TYPE_LOGGED = "error";
private static final int MAX_CHAINED_EXCEPTION_DEPTH = 8;
private final CrashlyticsReportDataCapture dataCapture;
private final IdManager idManager;
private final LogFileManager logFileManager;
private final UserMetadata reportMetadata;
private final CrashlyticsReportPersistence reportPersistence;
private final DataTransportCrashlyticsReportSender reportsSender;
public SessionReportingCoordinator(CrashlyticsReportDataCapture crashlyticsReportDataCapture, CrashlyticsReportPersistence crashlyticsReportPersistence, DataTransportCrashlyticsReportSender dataTransportCrashlyticsReportSender, LogFileManager logFileManager, UserMetadata userMetadata, IdManager idManager) {
this.dataCapture = crashlyticsReportDataCapture;
this.reportPersistence = crashlyticsReportPersistence;
this.reportsSender = dataTransportCrashlyticsReportSender;
this.logFileManager = logFileManager;
this.reportMetadata = userMetadata;
this.idManager = idManager;
}
private CrashlyticsReport.Session.Event addLogsAndCustomKeysToEvent(CrashlyticsReport.Session.Event event) {
return addLogsAndCustomKeysToEvent(event, this.logFileManager, this.reportMetadata);
}
private CrashlyticsReport.Session.Event addMetaDataToEvent(CrashlyticsReport.Session.Event event) {
return addRolloutsStateToEvent(addLogsAndCustomKeysToEvent(event, this.logFileManager, this.reportMetadata), this.reportMetadata);
}
private CrashlyticsReport.Session.Event addRolloutsStateToEvent(CrashlyticsReport.Session.Event event, UserMetadata userMetadata) {
List<CrashlyticsReport.Session.Event.RolloutAssignment> rolloutsState = userMetadata.getRolloutsState();
if (rolloutsState.isEmpty()) {
return event;
}
CrashlyticsReport.Session.Event.Builder builder = event.toBuilder();
builder.setRollouts(CrashlyticsReport.Session.Event.RolloutsState.builder().setRolloutAssignments(rolloutsState).build());
return builder.build();
}
private static CrashlyticsReport.ApplicationExitInfo convertApplicationExitInfo(ApplicationExitInfo applicationExitInfo) {
String applicationExitInfo2;
int importance;
String processName;
int reason;
long timestamp;
int pid;
long pss;
long rss;
InputStream traceInputStream;
String str = null;
try {
traceInputStream = applicationExitInfo.getTraceInputStream();
if (traceInputStream != null) {
str = convertInputStreamToString(traceInputStream);
}
} catch (IOException e4) {
Logger logger = Logger.getLogger();
StringBuilder sb = new StringBuilder("Could not get input trace in application exit info: ");
applicationExitInfo2 = applicationExitInfo.toString();
sb.append(applicationExitInfo2);
sb.append(" Error: ");
sb.append(e4);
logger.w(sb.toString());
}
CrashlyticsReport.ApplicationExitInfo.Builder builder = CrashlyticsReport.ApplicationExitInfo.builder();
importance = applicationExitInfo.getImportance();
CrashlyticsReport.ApplicationExitInfo.Builder importance2 = builder.setImportance(importance);
processName = applicationExitInfo.getProcessName();
CrashlyticsReport.ApplicationExitInfo.Builder processName2 = importance2.setProcessName(processName);
reason = applicationExitInfo.getReason();
CrashlyticsReport.ApplicationExitInfo.Builder reasonCode = processName2.setReasonCode(reason);
timestamp = applicationExitInfo.getTimestamp();
CrashlyticsReport.ApplicationExitInfo.Builder timestamp2 = reasonCode.setTimestamp(timestamp);
pid = applicationExitInfo.getPid();
CrashlyticsReport.ApplicationExitInfo.Builder pid2 = timestamp2.setPid(pid);
pss = applicationExitInfo.getPss();
CrashlyticsReport.ApplicationExitInfo.Builder pss2 = pid2.setPss(pss);
rss = applicationExitInfo.getRss();
return pss2.setRss(rss).setTraceFile(str).build();
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bArr = new byte[8192];
while (true) {
int read = inputStream.read(bArr);
if (read == -1) {
return byteArrayOutputStream.toString(StandardCharsets.UTF_8.name());
}
byteArrayOutputStream.write(bArr, 0, read);
}
}
public static SessionReportingCoordinator create(Context context, IdManager idManager, FileStore fileStore, AppData appData, LogFileManager logFileManager, UserMetadata userMetadata, StackTraceTrimmingStrategy stackTraceTrimmingStrategy, SettingsProvider settingsProvider, OnDemandCounter onDemandCounter, CrashlyticsAppQualitySessionsSubscriber crashlyticsAppQualitySessionsSubscriber) {
return new SessionReportingCoordinator(new CrashlyticsReportDataCapture(context, idManager, appData, stackTraceTrimmingStrategy, settingsProvider), new CrashlyticsReportPersistence(fileStore, settingsProvider, crashlyticsAppQualitySessionsSubscriber), DataTransportCrashlyticsReportSender.create(context, settingsProvider, onDemandCounter), logFileManager, userMetadata, idManager);
}
private CrashlyticsReportWithSessionId ensureHasFid(CrashlyticsReportWithSessionId crashlyticsReportWithSessionId) {
if (crashlyticsReportWithSessionId.getReport().getFirebaseInstallationId() != null) {
return crashlyticsReportWithSessionId;
}
return CrashlyticsReportWithSessionId.create(crashlyticsReportWithSessionId.getReport().withFirebaseInstallationId(this.idManager.fetchTrueFid()), crashlyticsReportWithSessionId.getSessionId(), crashlyticsReportWithSessionId.getReportFile());
}
private ApplicationExitInfo findRelevantApplicationExitInfo(String str, List<ApplicationExitInfo> list) {
long timestamp;
int reason;
long startTimestampMillis = this.reportPersistence.getStartTimestampMillis(str);
Iterator<ApplicationExitInfo> it = list.iterator();
while (it.hasNext()) {
ApplicationExitInfo c4 = P.c.c(it.next());
timestamp = c4.getTimestamp();
if (timestamp < startTimestampMillis) {
return null;
}
reason = c4.getReason();
if (reason == 6) {
return c4;
}
}
return null;
}
private static List<CrashlyticsReport.CustomAttribute> getSortedCustomAttributes(Map<String, String> map) {
ArrayList arrayList = new ArrayList();
arrayList.ensureCapacity(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
arrayList.add(CrashlyticsReport.CustomAttribute.builder().setKey(entry.getKey()).setValue(entry.getValue()).build());
}
Collections.sort(arrayList, new b(1));
return Collections.unmodifiableList(arrayList);
}
public static /* synthetic */ int lambda$getSortedCustomAttributes$0(CrashlyticsReport.CustomAttribute customAttribute, CrashlyticsReport.CustomAttribute customAttribute2) {
return customAttribute.getKey().compareTo(customAttribute2.getKey());
}
public boolean onReportSendComplete(Task<CrashlyticsReportWithSessionId> task) {
if (!task.isSuccessful()) {
Logger.getLogger().w("Crashlytics report could not be enqueued to DataTransport", task.getException());
return false;
}
CrashlyticsReportWithSessionId result = task.getResult();
Logger.getLogger().d("Crashlytics report successfully enqueued to DataTransport: " + result.getSessionId());
File reportFile = result.getReportFile();
if (reportFile.delete()) {
Logger.getLogger().d("Deleted report file: " + reportFile.getPath());
return true;
}
Logger.getLogger().w("Crashlytics could not delete report file: " + reportFile.getPath());
return true;
}
private void persistEvent(Throwable th, Thread thread, String str, String str2, long j4, boolean z3) {
this.reportPersistence.persistEvent(addMetaDataToEvent(this.dataCapture.captureEventData(th, thread, str2, j4, 4, 8, z3)), str, str2.equals("crash"));
}
public void finalizeSessionWithNativeEvent(String str, List<NativeSessionFile> list, CrashlyticsReport.ApplicationExitInfo applicationExitInfo) {
Logger.getLogger().d("SessionReportingCoordinator#finalizeSessionWithNativeEvent");
ArrayList arrayList = new ArrayList();
Iterator<NativeSessionFile> it = list.iterator();
while (it.hasNext()) {
CrashlyticsReport.FilesPayload.File asFilePayload = it.next().asFilePayload();
if (asFilePayload != null) {
arrayList.add(asFilePayload);
}
}
this.reportPersistence.finalizeSessionWithNativeEvent(str, CrashlyticsReport.FilesPayload.builder().setFiles(Collections.unmodifiableList(arrayList)).build(), applicationExitInfo);
}
public void finalizeSessions(long j4, String str) {
this.reportPersistence.finalizeReports(str, j4);
}
public boolean hasReportsToSend() {
return this.reportPersistence.hasFinalizedReports();
}
public SortedSet<String> listSortedOpenSessionIds() {
return this.reportPersistence.getOpenSessionIds();
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsLifecycleEvents
public void onBeginSession(String str, long j4) {
this.reportPersistence.persistReport(this.dataCapture.captureReportData(str, j4));
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsLifecycleEvents
public void onCustomKey(String str, String str2) {
this.reportMetadata.setCustomKey(str, str2);
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsLifecycleEvents
public void onLog(long j4, String str) {
this.logFileManager.writeToLog(j4, str);
}
@Override // com.google.firebase.crashlytics.internal.common.CrashlyticsLifecycleEvents
public void onUserId(String str) {
this.reportMetadata.setUserId(str);
}
public void persistFatalEvent(Throwable th, Thread thread, String str, long j4) {
Logger.getLogger().v("Persisting fatal event for session " + str);
persistEvent(th, thread, str, "crash", j4, true);
}
public void persistNonFatalEvent(Throwable th, Thread thread, String str, long j4) {
Logger.getLogger().v("Persisting non-fatal event for session " + str);
persistEvent(th, thread, str, "error", j4, false);
}
public void persistRelevantAppExitInfoEvent(String str, List<ApplicationExitInfo> list, LogFileManager logFileManager, UserMetadata userMetadata) {
ApplicationExitInfo findRelevantApplicationExitInfo = findRelevantApplicationExitInfo(str, list);
if (findRelevantApplicationExitInfo == null) {
Logger.getLogger().v("No relevant ApplicationExitInfo occurred during session: " + str);
return;
}
CrashlyticsReport.Session.Event captureAnrEventData = this.dataCapture.captureAnrEventData(convertApplicationExitInfo(findRelevantApplicationExitInfo));
Logger.getLogger().d("Persisting anr for session " + str);
this.reportPersistence.persistEvent(addRolloutsStateToEvent(addLogsAndCustomKeysToEvent(captureAnrEventData, logFileManager, userMetadata), userMetadata), str, true);
}
public void removeAllReports() {
this.reportPersistence.deleteAllReports();
}
public Task<Void> sendReports(Executor executor) {
return sendReports(executor, null);
}
private CrashlyticsReport.Session.Event addLogsAndCustomKeysToEvent(CrashlyticsReport.Session.Event event, LogFileManager logFileManager, UserMetadata userMetadata) {
CrashlyticsReport.Session.Event.Builder builder = event.toBuilder();
String logString = logFileManager.getLogString();
if (logString != null) {
builder.setLog(CrashlyticsReport.Session.Event.Log.builder().setContent(logString).build());
} else {
Logger.getLogger().v("No log data to include with this event.");
}
List<CrashlyticsReport.CustomAttribute> sortedCustomAttributes = getSortedCustomAttributes(userMetadata.getCustomKeys());
List<CrashlyticsReport.CustomAttribute> sortedCustomAttributes2 = getSortedCustomAttributes(userMetadata.getInternalKeys());
if (!sortedCustomAttributes.isEmpty() || !sortedCustomAttributes2.isEmpty()) {
builder.setApp(event.getApp().toBuilder().setCustomAttributes(sortedCustomAttributes).setInternalKeys(sortedCustomAttributes2).build());
}
return builder.build();
}
public Task<Void> sendReports(Executor executor, String str) {
List<CrashlyticsReportWithSessionId> loadFinalizedReports = this.reportPersistence.loadFinalizedReports();
ArrayList arrayList = new ArrayList();
for (CrashlyticsReportWithSessionId crashlyticsReportWithSessionId : loadFinalizedReports) {
if (str == null || str.equals(crashlyticsReportWithSessionId.getSessionId())) {
arrayList.add(this.reportsSender.enqueueReport(ensureHasFid(crashlyticsReportWithSessionId), str != null).continueWith(executor, new k(this, 17)));
}
}
return Tasks.whenAll(arrayList);
}
}

View File

@@ -0,0 +1,9 @@
package com.google.firebase.crashlytics.internal.common;
/* loaded from: classes3.dex */
public class SystemCurrentTimeProvider implements CurrentTimeProvider {
@Override // com.google.firebase.crashlytics.internal.common.CurrentTimeProvider
public long getCurrentTimeMillis() {
return System.currentTimeMillis();
}
}

View File

@@ -0,0 +1,140 @@
package com.google.firebase.crashlytics.internal.common;
import I2.k;
import android.annotation.SuppressLint;
import android.os.Looper;
import androidx.fragment.app.RunnableC0143e;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/* loaded from: classes3.dex */
public final class Utils {
private static final ExecutorService TASK_CONTINUATION_EXECUTOR_SERVICE = ExecutorUtils.buildSingleThreadExecutorService("awaitEvenIfOnMainThread task continuation executor");
private static final int TIMEOUT_SEC = 4;
private Utils() {
}
public static <T> T awaitEvenIfOnMainThread(Task<T> task) throws InterruptedException, TimeoutException {
CountDownLatch countDownLatch = new CountDownLatch(1);
task.continueWith(TASK_CONTINUATION_EXECUTOR_SERVICE, new k(countDownLatch, 18));
if (Looper.getMainLooper() == Looper.myLooper()) {
countDownLatch.await(3L, TimeUnit.SECONDS);
} else {
countDownLatch.await(4L, TimeUnit.SECONDS);
}
if (task.isSuccessful()) {
return task.getResult();
}
if (task.isCanceled()) {
throw new CancellationException("Task is already canceled");
}
if (task.isComplete()) {
throw new IllegalStateException(task.getException());
}
throw new TimeoutException();
}
public static boolean awaitUninterruptibly(CountDownLatch countDownLatch, long j4, TimeUnit timeUnit) {
boolean z3 = false;
try {
long nanos = timeUnit.toNanos(j4);
while (true) {
try {
break;
} catch (InterruptedException unused) {
z3 = true;
nanos = (System.nanoTime() + nanos) - System.nanoTime();
}
}
return countDownLatch.await(nanos, TimeUnit.NANOSECONDS);
} finally {
if (z3) {
Thread.currentThread().interrupt();
}
}
}
public static /* synthetic */ Object b(CountDownLatch countDownLatch, Task task) {
return lambda$awaitEvenIfOnMainThread$4(countDownLatch, task);
}
public static <T> Task<T> callTask(Executor executor, Callable<Task<T>> callable) {
TaskCompletionSource taskCompletionSource = new TaskCompletionSource();
executor.execute(new RunnableC0143e(callable, executor, taskCompletionSource, 3));
return taskCompletionSource.getTask();
}
public static /* synthetic */ Object lambda$awaitEvenIfOnMainThread$4(CountDownLatch countDownLatch, Task task) throws Exception {
countDownLatch.countDown();
return null;
}
public static /* synthetic */ Object lambda$callTask$2(TaskCompletionSource taskCompletionSource, Task task) throws Exception {
if (task.isSuccessful()) {
taskCompletionSource.setResult(task.getResult());
return null;
}
if (task.getException() == null) {
return null;
}
taskCompletionSource.setException(task.getException());
return null;
}
public static /* synthetic */ void lambda$callTask$3(Callable callable, Executor executor, TaskCompletionSource taskCompletionSource) {
try {
((Task) callable.call()).continueWith(executor, new d(1, taskCompletionSource));
} catch (Exception e4) {
taskCompletionSource.setException(e4);
}
}
public static /* synthetic */ Void lambda$race$0(TaskCompletionSource taskCompletionSource, Task task) throws Exception {
if (task.isSuccessful()) {
taskCompletionSource.trySetResult(task.getResult());
return null;
}
if (task.getException() == null) {
return null;
}
taskCompletionSource.trySetException(task.getException());
return null;
}
public static /* synthetic */ Void lambda$race$1(TaskCompletionSource taskCompletionSource, Task task) throws Exception {
if (task.isSuccessful()) {
taskCompletionSource.trySetResult(task.getResult());
return null;
}
if (task.getException() == null) {
return null;
}
taskCompletionSource.trySetException(task.getException());
return null;
}
@SuppressLint({"TaskMainThread"})
public static <T> Task<T> race(Task<T> task, Task<T> task2) {
TaskCompletionSource taskCompletionSource = new TaskCompletionSource();
d dVar = new d(0, taskCompletionSource);
task.continueWith(dVar);
task2.continueWith(dVar);
return taskCompletionSource.getTask();
}
public static <T> Task<T> race(Executor executor, Task<T> task, Task<T> task2) {
TaskCompletionSource taskCompletionSource = new TaskCompletionSource();
d dVar = new d(2, taskCompletionSource);
task.continueWith(executor, dVar);
task2.continueWith(executor, dVar);
return taskCompletionSource.getTask();
}
}

View File

@@ -0,0 +1,25 @@
package com.google.firebase.crashlytics.internal.common;
import java.io.File;
import java.io.FilenameFilter;
/* loaded from: classes3.dex */
public final /* synthetic */ class a implements FilenameFilter {
/* renamed from: a, reason: collision with root package name */
public final /* synthetic */ int f5967a;
public /* synthetic */ a(int i) {
this.f5967a = i;
}
@Override // java.io.FilenameFilter
public final boolean accept(File file, String str) {
switch (this.f5967a) {
case 0:
return CrashlyticsAppQualitySessionsStore.a(file, str);
default:
return CrashlyticsController.a(file, str);
}
}
}

View File

@@ -0,0 +1,28 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.firebase.crashlytics.internal.model.CrashlyticsReport;
import java.io.File;
import java.util.Comparator;
/* loaded from: classes3.dex */
public final /* synthetic */ class b implements Comparator {
/* renamed from: a, reason: collision with root package name */
public final /* synthetic */ int f5968a;
public /* synthetic */ b(int i) {
this.f5968a = i;
}
@Override // java.util.Comparator
public final int compare(Object obj, Object obj2) {
int lambda$static$1;
switch (this.f5968a) {
case 0:
lambda$static$1 = CrashlyticsAppQualitySessionsStore.lambda$static$1((File) obj, (File) obj2);
return lambda$static$1;
default:
return SessionReportingCoordinator.a((CrashlyticsReport.CustomAttribute) obj, (CrashlyticsReport.CustomAttribute) obj2);
}
}
}

View File

@@ -0,0 +1,40 @@
package com.google.firebase.crashlytics.internal.common;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
/* loaded from: classes3.dex */
public final /* synthetic */ class d implements Continuation {
/* renamed from: a, reason: collision with root package name */
public final /* synthetic */ int f5970a;
/* renamed from: b, reason: collision with root package name */
public final /* synthetic */ TaskCompletionSource f5971b;
public /* synthetic */ d(int i, TaskCompletionSource taskCompletionSource) {
this.f5970a = i;
this.f5971b = taskCompletionSource;
}
@Override // com.google.android.gms.tasks.Continuation
public final Object then(Task task) {
Void lambda$race$0;
Object lambda$callTask$2;
Void lambda$race$1;
int i = this.f5970a;
TaskCompletionSource taskCompletionSource = this.f5971b;
switch (i) {
case 0:
lambda$race$0 = Utils.lambda$race$0(taskCompletionSource, task);
return lambda$race$0;
case 1:
lambda$callTask$2 = Utils.lambda$callTask$2(taskCompletionSource, task);
return lambda$callTask$2;
default:
lambda$race$1 = Utils.lambda$race$1(taskCompletionSource, task);
return lambda$race$1;
}
}
}