Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Avoid possible memory leaks by ensuring stream closures

Stream close() methods should always be called in finally block
to ensure we don't accidentally leak a stream.

Time to fix some old sloppy code.

Patch Set 2:
 + ensure closure of some other streams
Patch Set 3:
 + missing import java.io.IOException
Patch Set 4:
 + missing import
Patch Set 5:
 + missing ';'
 + whitespace cleanup
Patch Set 6:
 - Reverted changes to MemoryUsage (final requirement
     prevents my implentation)
 + fixed Object allocation in Root.java
Patch Set 7:
 + fixed curly bracket style violations
Patch Set 8:
 x fixed my own sloppy code :/

Change-Id: I3460b558ed5b4489296388c9a52fbb773cefd31f
  • Loading branch information...
commit dd575d384a96db103d77899d7ba32e47577ee876 1 parent 9087e85
Jon Stanford JBirdVegas authored
16 graphics/java/android/graphics/drawable/NinePatchDrawable.java
View
@@ -301,16 +301,18 @@ public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
final Rect padding = new Rect();
final Rect layoutInsets = new Rect();
Bitmap bitmap = null;
-
+ InputStream is = null;
try {
final TypedValue value = new TypedValue();
- final InputStream is = r.openRawResource(id, value);
-
+ is = r.openRawResource(id, value);
bitmap = BitmapFactory.decodeResourceStream(r, value, is, padding, options);
-
- is.close();
- } catch (IOException e) {
- // Ignore
+ } finally {
+ if (is != null) {
+ try {
+ is.close();
+ } catch (IOException ignored) {
+ }
+ }
}
if (bitmap == null) {
136 obex/javax/obex/HeaderSet.java
View
@@ -501,84 +501,88 @@ public Object getHeader(int headerID) throws IOException {
* the operation or the connection has been closed
*/
public int[] getHeaderList() throws IOException {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream out = null;
+ try{
+ out = new ByteArrayOutputStream();
- if (mCount != null) {
- out.write(COUNT);
- }
- if (mName != null) {
- out.write(NAME);
- }
- if (mType != null) {
- out.write(TYPE);
- }
- if (mLength != null) {
- out.write(LENGTH);
- }
- if (mIsoTime != null) {
- out.write(TIME_ISO_8601);
- }
- if (mByteTime != null) {
- out.write(TIME_4_BYTE);
- }
- if (mDescription != null) {
- out.write(DESCRIPTION);
- }
- if (mTarget != null) {
- out.write(TARGET);
- }
- if (mHttpHeader != null) {
- out.write(HTTP);
- }
- if (mWho != null) {
- out.write(WHO);
- }
- if (mAppParam != null) {
- out.write(APPLICATION_PARAMETER);
- }
- if (mObjectClass != null) {
- out.write(OBJECT_CLASS);
- }
-
- for (int i = 0x30; i < 0x40; i++) {
- if (mUnicodeUserDefined[i - 0x30] != null) {
- out.write(i);
+ if (mCount != null) {
+ out.write(COUNT);
+ }
+ if (mName != null) {
+ out.write(NAME);
+ }
+ if (mType != null) {
+ out.write(TYPE);
+ }
+ if (mLength != null) {
+ out.write(LENGTH);
+ }
+ if (mIsoTime != null) {
+ out.write(TIME_ISO_8601);
+ }
+ if (mByteTime != null) {
+ out.write(TIME_4_BYTE);
+ }
+ if (mDescription != null) {
+ out.write(DESCRIPTION);
+ }
+ if (mTarget != null) {
+ out.write(TARGET);
+ }
+ if (mHttpHeader != null) {
+ out.write(HTTP);
+ }
+ if (mWho != null) {
+ out.write(WHO);
+ }
+ if (mAppParam != null) {
+ out.write(APPLICATION_PARAMETER);
+ }
+ if (mObjectClass != null) {
+ out.write(OBJECT_CLASS);
}
- }
- for (int i = 0x70; i < 0x80; i++) {
- if (mSequenceUserDefined[i - 0x70] != null) {
- out.write(i);
+ for (int i = 0x30; i < 0x40; i++) {
+ if (mUnicodeUserDefined[i - 0x30] != null) {
+ out.write(i);
+ }
}
- }
- for (int i = 0xB0; i < 0xC0; i++) {
- if (mByteUserDefined[i - 0xB0] != null) {
- out.write(i);
+ for (int i = 0x70; i < 0x80; i++) {
+ if (mSequenceUserDefined[i - 0x70] != null) {
+ out.write(i);
+ }
}
- }
- for (int i = 0xF0; i < 0x100; i++) {
- if (mIntegerUserDefined[i - 0xF0] != null) {
- out.write(i);
+ for (int i = 0xB0; i < 0xC0; i++) {
+ if (mByteUserDefined[i - 0xB0] != null) {
+ out.write(i);
+ }
}
- }
- byte[] headers = out.toByteArray();
- out.close();
+ for (int i = 0xF0; i < 0x100; i++) {
+ if (mIntegerUserDefined[i - 0xF0] != null) {
+ out.write(i);
+ }
+ }
- if ((headers == null) || (headers.length == 0)) {
- return null;
- }
+ byte[] headers = out.toByteArray();
+ if ((headers == null) || (headers.length == 0)) {
+ return null;
+ }
- int[] result = new int[headers.length];
- for (int i = 0; i < headers.length; i++) {
- // Convert the byte to a positive integer. That is, an integer
- // between 0 and 256.
- result[i] = headers[i] & 0xFF;
+ int[] result = new int[headers.length];
+ for (int i = 0; i < headers.length; i++) {
+ // Convert the byte to a positive integer. That is, an integer
+ // between 0 and 256.
+ result[i] = headers[i] & 0xFF;
+ }
+ return result;
+ } finally {
+ if (out != null) {
+ out.close();
+ }
}
-
- return result;
}
/**
33 packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
View
@@ -58,6 +58,7 @@
import com.android.systemui.R;
import java.io.File;
+import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -163,14 +164,14 @@
protected SaveImageInBackgroundData doInBackground(SaveImageInBackgroundData... params) {
if (params.length != 1) return null;
- // By default, AsyncTask sets the worker thread to have background thread priority, so bump
- // it back up so that we save a little quicker.
- Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
+ // By default, AsyncTask sets the worker thread to have background thread priority, so
+ // give highest possible priority to worker thread
+ Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_DISPLAY);
Context context = params[0].context;
Bitmap image = params[0].image;
Resources r = context.getResources();
-
+ OutputStream outStream = null;
try {
// Save the screenshot to the MediaStore
ContentValues values = new ContentValues();
@@ -197,10 +198,8 @@ protected SaveImageInBackgroundData doInBackground(SaveImageInBackgroundData...
PendingIntent.getActivity(context, 0, chooserIntent,
PendingIntent.FLAG_CANCEL_CURRENT));
- OutputStream out = resolver.openOutputStream(uri);
- image.compress(Bitmap.CompressFormat.PNG, 100, out);
- out.flush();
- out.close();
+ outStream = resolver.openOutputStream(uri);
+ image.compress(Bitmap.CompressFormat.PNG, 100, outStream);
// update file size in the database
values.clear();
@@ -209,12 +208,22 @@ protected SaveImageInBackgroundData doInBackground(SaveImageInBackgroundData...
params[0].imageUri = uri;
params[0].result = 0;
- } catch (Exception e) {
- // IOException/UnsupportedOperationException may be thrown if external storage is not
- // mounted
+ } catch (IOException e) {
+ // may be thrown if external storage is not mounted
+ params[0].result = 1;
+ } catch (UnsupportedOperationException noOperation) {
+ // may be thrown if external storage is not mounted
params[0].result = 1;
+ } finally {
+ if (outStream != null) {
+ try {
+ outStream.flush();
+ outStream.close();
+ } catch (IOException ioe) {
+ // let it go
+ }
+ }
}
-
return params[0];
}
11 packages/SystemUI/src/com/android/systemui/statusbar/GestureRecorder.java
View
@@ -227,10 +227,10 @@ public void saveLater() {
public void save() {
synchronized (mGestures) {
+ BufferedWriter w = null;
try {
- BufferedWriter w = new BufferedWriter(new FileWriter(mLogfile, /*append=*/ true));
+ w = new BufferedWriter(new FileWriter(mLogfile, /*append=*/ true));
w.append(toJsonLocked() + "\n");
- w.close();
mGestures.clear();
// If we have a pending gesture, push it back
if (mCurrentGesture != null && !mCurrentGesture.isComplete()) {
@@ -242,6 +242,13 @@ public void save() {
} catch (IOException e) {
Slog.e(TAG, String.format("Couldn't write gestures to %s", mLogfile), e);
mLastSaveLen = -1;
+ } finally {
+ if (w != null) {
+ try {
+ w.close();
+ } catch (IOException ignored) {
+ }
+ }
}
}
}
8 services/java/com/android/server/DevicePolicyManagerService.java
View
@@ -800,6 +800,14 @@ private void saveSettingsLocked(int userHandle) {
// Ignore
}
journal.rollback();
+ } finally {
+ try {
+ if (stream != null) {
+ stream.close();
+ }
+ } catch (IOException ex) {
+ // Ignore
+ }
}
}
23 services/java/com/android/server/LightsService.java
View
@@ -26,6 +26,7 @@
import java.io.FileInputStream;
import java.io.FileOutputStream;
+import java.io.IOException;
public class LightsService {
private static final String TAG = "LightsService";
@@ -142,13 +143,20 @@ private void setLightLocked(int color, int mode, int onMS, int offMS, int bright
private static final String FLASHLIGHT_FILE = "/sys/class/leds/spotlight/brightness";
public boolean getFlashlightEnabled() {
+ FileInputStream fis = null;
try {
- FileInputStream fis = new FileInputStream(FLASHLIGHT_FILE);
+ fis = new FileInputStream(FLASHLIGHT_FILE);
int result = fis.read();
- fis.close();
return (result != '0');
} catch (Exception e) {
return false;
+ } finally {
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (IOException ignored) {
+ }
+ }
}
}
@@ -159,15 +167,22 @@ public void setFlashlightEnabled(boolean on) {
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("Requires FLASHLIGHT or HARDWARE_TEST permission");
}
+ FileOutputStream fos = null;
try {
- FileOutputStream fos = new FileOutputStream(FLASHLIGHT_FILE);
+ fos = new FileOutputStream(FLASHLIGHT_FILE);
byte[] bytes = new byte[2];
bytes[0] = (byte)(on ? '1' : '0');
bytes[1] = '\n';
fos.write(bytes);
- fos.close();
} catch (Exception e) {
// fail silently
+ } finally {
+ if (fos != null) {
+ try {
+ fos.close();
+ } catch (IOException ignored) {
+ }
+ }
}
}
};
14 services/java/com/android/server/am/ActivityManagerService.java
View
@@ -3200,6 +3200,7 @@ final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
final File tracesFile = new File(tracesPath);
final File tracesDir = tracesFile.getParentFile();
final File tracesTmp = new File(tracesDir, "__tmp__");
+ FileOutputStream fos = null;
try {
if (!tracesDir.exists()) {
tracesFile.mkdirs();
@@ -3221,16 +3222,23 @@ final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
sb.append(" since ");
sb.append(msg);
- FileOutputStream fos = new FileOutputStream(tracesFile);
+ fos = new FileOutputStream(tracesFile);
fos.write(sb.toString().getBytes());
if (app == null) {
fos.write("\n*** No application process!".getBytes());
}
- fos.close();
- FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
} catch (IOException e) {
Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
return;
+ } finally {
+ try {
+ if (fos != null) {
+ fos.close();
+ }
+ FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
+ } catch (IOException ignored) {
+ // let it go
+ }
}
if (app != null) {
48 tools/preload/Root.java
View
@@ -132,16 +132,22 @@ void indexProcess(Record record) {
* Writes this graph to a file.
*/
void toFile(String fileName) throws IOException {
- FileOutputStream out = new FileOutputStream(fileName);
- ObjectOutputStream oout = new ObjectOutputStream(
+ FileOutputStream out = null;
+ ObjectOutputStream oout = null;
+ try {
+ out = new FileOutputStream(fileName);
+ oout = new ObjectOutputStream(
new BufferedOutputStream(out));
-
- System.err.println("Writing object model...");
-
- oout.writeObject(this);
-
- oout.close();
-
+ System.err.println("Writing object model...");
+ oout.writeObject(this);
+ } finally {
+ if (out != null) {
+ out.close();
+ }
+ if (oout != null) {
+ oout.close();
+ }
+ }
System.err.println("Done!");
}
@@ -150,14 +156,20 @@ void toFile(String fileName) throws IOException {
*/
static Root fromFile(String fileName)
throws IOException, ClassNotFoundException {
- FileInputStream fin = new FileInputStream(fileName);
- ObjectInputStream oin = new ObjectInputStream(
- new BufferedInputStream(fin));
-
- Root root = (Root) oin.readObject();
-
- oin.close();
-
- return root;
+ FileInputStream fin = null;
+ ObjectInputStream oin = null;
+ try {
+ fin = new FileInputStream(fileName);
+ oin = new ObjectInputStream(
+ new BufferedInputStream(fin));
+ return (Root) oin.readObject();
+ } finally {
+ if (fin != null) {
+ fin.close();
+ }
+ if (oin != null) {
+ oin.close();
+ }
+ }
}
}
6 wifi/java/android/net/wifi/WifiConfigStore.java
View
@@ -813,7 +813,8 @@ private static void onWriteCalled(List<WifiConfiguration> networks) {
if (out != null) {
try {
out.close();
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
//Quit if no more writes sent
@@ -954,7 +955,8 @@ private void readIpAndProxyConfigurations() {
if (in != null) {
try {
in.close();
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
}
}
Please sign in to comment.
Something went wrong with that request. Please try again.