summaryrefslogtreecommitdiffstats
path: root/src/com/android/browser/CrashLogExceptionHandler.java
blob: 920757077006e13ef4a14e4085fa395ff53ae2a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*
 * Copyright (c) 2014, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of The Linux Foundation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.android.browser;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.SystemClock;
import android.net.http.AndroidHttpClient;
import android.util.Log;

import org.codeaurora.swe.BrowserCommandLine;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.ClientProtocolException;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.Integer;
import java.lang.StringBuilder;
import java.lang.System;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Calendar;

public class CrashLogExceptionHandler implements Thread.UncaughtExceptionHandler {

    private static final String CRASH_LOG_FILE = "crash.log";
    private static final String CRASH_LOG_SERVER_CMD = "crash-log-server";
    private static final String CRASH_LOG_MAX_FILE_SIZE_CMD = "crash-log-max-file-size";

    private final static String LOGTAG = "CrashLog";

    private Context mAppContext = null;

    private UncaughtExceptionHandler mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

    private String mLogServer = new String();

    private boolean mOverrideHandler = false;

    private int mMaxLogFileSize = 1024 * 1024;

    public CrashLogExceptionHandler(Context ctx) {
        mAppContext = ctx;
        BrowserCommandLine cl = new BrowserCommandLine();
        if (cl.hasSwitch(CRASH_LOG_SERVER_CMD)) {
            mLogServer = cl.getSwitchValue(CRASH_LOG_SERVER_CMD);
            if (mLogServer != null) {
                uploadPastCrashLog();
                mOverrideHandler = true;
            }
        }

        try {
            int size = Integer.parseInt(cl.getSwitchValue(CRASH_LOG_MAX_FILE_SIZE_CMD,
                                                      Integer.toString(mMaxLogFileSize)));
            mMaxLogFileSize = size;
        } catch (NumberFormatException nfe) {
            Log.e(LOGTAG,"Max log file size is not configured properly. Using default: "
                  + mMaxLogFileSize);
        }

    }

    private void saveCrashLog(String crashLog) {
        // Check if log file exists and it's current size
        try {
            File file = new File(mAppContext.getFilesDir(), CRASH_LOG_FILE);
            if (file.exists()) {
                if (file.length() > mMaxLogFileSize) {
                    Log.e(LOGTAG,"CRASH Log file size(" + file.length()
                          + ") exceeded max log file size("
                          + mMaxLogFileSize + ")");
                    return;
                }
            }
        } catch (NullPointerException npe) {
            Log.e(LOGTAG,"Exception while checking file size: " + npe);
        }

        FileOutputStream crashLogFile = null;
        try {
            crashLogFile = mAppContext.openFileOutput(CRASH_LOG_FILE, Context.MODE_APPEND);
            crashLogFile.write(crashLog.getBytes());
        } catch(IOException ioe) {
            Log.e(LOGTAG,"Exception while writing file: " + ioe);
        } finally {
            if (crashLogFile != null) {
                try {
                    crashLogFile.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private void uploadPastCrashLog() {
        FileInputStream crashLogFile = null;
        BufferedReader reader = null;
        try {
            crashLogFile = mAppContext.openFileInput(CRASH_LOG_FILE);

            reader = new BufferedReader(new InputStreamReader(crashLogFile));
            StringBuilder crashLog = new StringBuilder();
            String line = reader.readLine();
            if (line != null) {
                crashLog.append(line);
            }

            // Typically there's only one line (JSON string) in the crash
            // log file. This loop would not be executed.
            while ((line = reader.readLine()) != null) {
                crashLog.append("\n").append(line);
            }

            uploadCrashLog(crashLog.toString(), 3000);
        } catch(FileNotFoundException fnfe) {
            Log.v(LOGTAG,"No previous crash found");
        } catch(IOException ioe) {
            Log.e(LOGTAG,"Exception while reading crash file: " + ioe);
        } finally {
            if (crashLogFile != null) {
                try {
                    crashLogFile.close();
                } catch (IOException ignore) {
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private void uploadCrashLog(String data, int after) {
        final String crashLog = data;
        final int waitFor = after;
        new Thread(new Runnable() {
                public void run(){
                    try {
                        SystemClock.sleep(waitFor);
                        AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");;
                        HttpPost httpPost = new HttpPost(mLogServer);
                        HttpEntity se = new StringEntity(crashLog);
                        httpPost.setEntity(se);
                        HttpResponse response = httpClient.execute(httpPost);

                        File crashLogFile = new File(mAppContext.getFilesDir(),
                                                     CRASH_LOG_FILE);
                        if (crashLogFile != null) {
                            crashLogFile.delete();
                        } else {
                            Log.e(LOGTAG,"crash log file could not be opened for deletion");
                        }
                    } catch (ClientProtocolException pe) {
                        Log.e(LOGTAG,"Exception while sending http post: " + pe);
                    } catch (IOException ioe1) {
                        Log.e(LOGTAG,"Exception while sending http post: " + ioe1);
                    }
                }
            }).start();
    }

    public void uncaughtException(Thread t, Throwable e) {
        if (!mOverrideHandler) {
            mDefaultHandler.uncaughtException(t, e);
            return;
        }

        String crashLog = new String();

        try {
            Calendar calendar = Calendar.getInstance();
            JSONObject jsonStackObj = new JSONObject();
            String date = calendar.getTime().toString();
            String aboutSWE = mAppContext.getResources().getString(R.string.about_text);
            String sweVer = aboutSWE.substring(aboutSWE.indexOf("Hash"),
                                               aboutSWE.length());

            jsonStackObj.put("date", date);
            jsonStackObj.put("device", android.os.Build.MODEL);
            jsonStackObj.put("android-ver", android.os.Build.VERSION.RELEASE);
            jsonStackObj.put("browser-ver", sweVer);
            jsonStackObj.put("thread", t.toString());
            jsonStackObj.put("cause", e.getCause());

            Throwable cause = e.getCause();
            if(cause != null) {
                StackTraceElement[] arr = cause.getStackTrace();
                JSONArray jsonStack = new JSONArray(arr);
                jsonStackObj.put("stack", jsonStack);
            }

            JSONObject jsonMainObj = new JSONObject();
            jsonMainObj.put("backtraces", jsonStackObj);

            Log.e(LOGTAG, "Exception: " + jsonMainObj.toString(4));
            crashLog = jsonMainObj.toString();

        } catch (JSONException je) {
            Log.e(LOGTAG, "Failed in JSON encoding: " + je);
        }

        saveCrashLog(crashLog);

        uploadCrashLog(crashLog, 0);

        mDefaultHandler.uncaughtException(t, e);
    }
}