1 /*
2  * Copyright (C) 2023 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.server.am;
18 
19 import android.os.OomKillRecord;
20 import android.util.Slog;
21 
22 /** Connection to the out-of-memory (OOM) events' file */
23 public final class OomConnection {
24     private static final String TAG = "OomConnection";
25 
26     /** Connection listener interface */
27     public interface OomConnectionListener {
28 
29         /**
30          * Callback function to handle the newest OOM kills.
31          *
32          * @param oomKills List of oom kills received from `waitOom()`
33          */
handleOomEvent(OomKillRecord[] oomKills)34         void handleOomEvent(OomKillRecord[] oomKills);
35     }
36 
37     private final OomConnectionListener mOomListener;
38 
39     private final OomConnectionThread mOomConnectionThread;
40 
waitOom()41     private static native OomKillRecord[] waitOom();
42 
OomConnection(OomConnectionListener listener)43     public OomConnection(OomConnectionListener listener) {
44         mOomListener = listener;
45         mOomConnectionThread = new OomConnectionThread();
46         mOomConnectionThread.start();
47     }
48 
49     private final class OomConnectionThread extends Thread {
run()50         public void run() {
51             while (true) {
52                 OomKillRecord[] oom_kills = null;
53                 try {
54                     oom_kills = waitOom();
55                     mOomListener.handleOomEvent(oom_kills);
56                 } catch (RuntimeException e) {
57                     Slog.e(TAG, "failed waiting for OOM events: " + e);
58                     break;
59                 }
60             }
61         }
62     }
63 }
64