1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16 
17 package com.android.systemui.util.leak;
18 
19 import static com.android.systemui.Dependency.LEAK_REPORT_EMAIL_NAME;
20 
21 import android.annotation.Nullable;
22 import android.app.Notification;
23 import android.app.NotificationChannel;
24 import android.app.NotificationManager;
25 import android.app.PendingIntent;
26 import android.content.ClipData;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.net.Uri;
30 import android.os.Debug;
31 import android.os.SystemProperties;
32 import android.os.UserHandle;
33 import android.util.Log;
34 
35 import androidx.core.content.FileProvider;
36 
37 import com.google.android.collect.Lists;
38 
39 import java.io.File;
40 import java.io.FileOutputStream;
41 import java.io.IOException;
42 import java.io.PrintWriter;
43 import java.util.ArrayList;
44 
45 import javax.inject.Inject;
46 import javax.inject.Named;
47 import javax.inject.Singleton;
48 
49 /**
50  * Dumps data to debug leaks and posts a notification to share the data.
51  */
52 @Singleton
53 public class LeakReporter {
54 
55     static final String TAG = "LeakReporter";
56 
57     public static final String FILEPROVIDER_AUTHORITY = "com.android.systemui.fileprovider";
58 
59     static final String LEAK_DIR = "leak";
60     static final String LEAK_HPROF = "leak.hprof";
61     static final String LEAK_DUMP = "leak.dump";
62 
63     private final Context mContext;
64     private final LeakDetector mLeakDetector;
65     private final String mLeakReportEmail;
66 
67     @Inject
LeakReporter(Context context, LeakDetector leakDetector, @Nullable @Named(LEAK_REPORT_EMAIL_NAME) String leakReportEmail)68     public LeakReporter(Context context, LeakDetector leakDetector,
69             @Nullable @Named(LEAK_REPORT_EMAIL_NAME) String leakReportEmail) {
70         mContext = context;
71         mLeakDetector = leakDetector;
72         mLeakReportEmail = leakReportEmail;
73     }
74 
dumpLeak(int garbageCount)75     public void dumpLeak(int garbageCount) {
76         try {
77             File leakDir = new File(mContext.getCacheDir(), LEAK_DIR);
78             leakDir.mkdir();
79 
80             File hprofFile = new File(leakDir, LEAK_HPROF);
81             Debug.dumpHprofData(hprofFile.getAbsolutePath());
82 
83             File dumpFile = new File(leakDir, LEAK_DUMP);
84             try (FileOutputStream fos = new FileOutputStream(dumpFile)) {
85                 PrintWriter w = new PrintWriter(fos);
86                 w.print("Build: "); w.println(SystemProperties.get("ro.build.description"));
87                 w.println();
88                 w.flush();
89                 mLeakDetector.dump(fos.getFD(), w, new String[0]);
90                 w.close();
91             }
92 
93             NotificationManager notiMan = mContext.getSystemService(NotificationManager.class);
94 
95             NotificationChannel channel = new NotificationChannel("leak", "Leak Alerts",
96                     NotificationManager.IMPORTANCE_HIGH);
97             channel.enableVibration(true);
98 
99             notiMan.createNotificationChannel(channel);
100             Notification.Builder builder = new Notification.Builder(mContext, channel.getId())
101                     .setAutoCancel(true)
102                     .setShowWhen(true)
103                     .setContentTitle("Memory Leak Detected")
104                     .setContentText(String.format(
105                             "SystemUI has detected %d leaked objects. Tap to send", garbageCount))
106                     .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
107                     .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
108                             getIntent(hprofFile, dumpFile),
109                             PendingIntent.FLAG_UPDATE_CURRENT, null, UserHandle.CURRENT));
110             notiMan.notify(TAG, 0, builder.build());
111         } catch (IOException e) {
112             Log.e(TAG, "Couldn't dump heap for leak", e);
113         }
114     }
115 
getIntent(File hprofFile, File dumpFile)116     private Intent getIntent(File hprofFile, File dumpFile) {
117         Uri dumpUri = FileProvider.getUriForFile(mContext, FILEPROVIDER_AUTHORITY, dumpFile);
118         Uri hprofUri = FileProvider.getUriForFile(mContext, FILEPROVIDER_AUTHORITY, hprofFile);
119 
120         Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
121         String mimeType = "application/vnd.android.leakreport";
122 
123         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
124         intent.addCategory(Intent.CATEGORY_DEFAULT);
125         intent.setType(mimeType);
126 
127         final String subject = "SystemUI leak report";
128         intent.putExtra(Intent.EXTRA_SUBJECT, subject);
129 
130         // EXTRA_TEXT should be an ArrayList, but some clients are expecting a single String.
131         // So, to avoid an exception on Intent.migrateExtraStreamToClipData(), we need to manually
132         // create the ClipData object with the attachments URIs.
133         final StringBuilder messageBody = new StringBuilder("Build info: ")
134                 .append(SystemProperties.get("ro.build.description"));
135         intent.putExtra(Intent.EXTRA_TEXT, messageBody.toString());
136         final ClipData clipData = new ClipData(null, new String[] { mimeType },
137                 new ClipData.Item(null, null, null, dumpUri));
138         final ArrayList<Uri> attachments = Lists.newArrayList(dumpUri);
139 
140         clipData.addItem(new ClipData.Item(null, null, null, hprofUri));
141         attachments.add(hprofUri);
142 
143         intent.setClipData(clipData);
144         intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, attachments);
145 
146         String leakReportEmail = mLeakReportEmail;
147         if (leakReportEmail != null) {
148             intent.putExtra(Intent.EXTRA_EMAIL, new String[] { leakReportEmail });
149         }
150 
151         return intent;
152     }
153 }
154