summaryrefslogtreecommitdiff
path: root/libartservice/service/java/com/android/server/art/prereboot/PreRebootDriver.java
blob: 2e4338316177176b9f5073390ccfa20fcef23ec2 (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
/*
 * Copyright (C) 2024 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.server.art.prereboot;

import static com.android.server.art.IDexoptChrootSetup.CHROOT_DIR;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
import android.os.ArtModuleServiceManager;
import android.os.Build;
import android.os.CancellationSignal;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
import android.util.Log;
import android.util.Slog;

import androidx.annotation.RequiresApi;

import com.android.internal.annotations.VisibleForTesting;
import com.android.server.art.ArtManagerLocal;
import com.android.server.art.ArtModuleServiceInitializer;
import com.android.server.art.GlobalInjector;
import com.android.server.art.IDexoptChrootSetup;
import com.android.server.art.Utils;

import dalvik.system.DelegateLastClassLoader;

/**
 * Drives Pre-reboot Dexopt, through reflection.
 *
 * During Pre-reboot Dexopt, the old version of this code is run.
 *
 * @hide
 */
@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
public class PreRebootDriver {
    private static final String TAG = ArtManagerLocal.TAG;

    @NonNull private final Injector mInjector;

    public PreRebootDriver(@NonNull Context context) {
        this(new Injector(context));
    }

    @VisibleForTesting
    public PreRebootDriver(@NonNull Injector injector) {
        mInjector = injector;
    }

    /**
     * Runs Pre-reboot Dexopt and returns whether it is successful.
     *
     * @param otaSlot The slot that contains the OTA update, "_a" or "_b", or null for a Mainline
     *         update.
     */
    public boolean run(@Nullable String otaSlot, @NonNull CancellationSignal cancellationSignal) {
        try {
            setUp(otaSlot);
            runFromChroot(cancellationSignal);
            return true;
        } catch (RemoteException e) {
            Utils.logArtdException(e);
        } catch (ServiceSpecificException e) {
            Log.e(TAG, "Failed to set up chroot", e);
        } catch (ReflectiveOperationException e) {
            Log.e(TAG, "Failed to run pre-reboot dexopt", e);
        } finally {
            tearDown();
        }
        return false;
    }

    private void setUp(@Nullable String otaSlot) throws RemoteException {
        mInjector.getDexoptChrootSetup().setUp(otaSlot);
    }

    private void tearDown() {
        // In general, the teardown unmounts apexes and partitions, and open files can keep the
        // mounts busy so that they cannot be unmounted. Therefore, two things can prevent the
        // teardown from succeeding: a running Pre-reboot artd process and the new `service-art.jar`
        // opened and mapped by system server. They are managed by the service manager and the
        // runtime respectively. There aren't reliable APIs to kill the former or close the latter,
        // so we have to do them by triggering GC and finalization, with sleep and retry mechanism.
        for (int numRetries = 3; numRetries > 0;) {
            try {
                Runtime.getRuntime().gc();
                Runtime.getRuntime().runFinalization();
                // Wait for the service manager to shut down artd. The shutdown is asynchronous.
                Utils.sleep(5000);
                mInjector.getDexoptChrootSetup().tearDown();
                return;
            } catch (RemoteException e) {
                Utils.logArtdException(e);
            } catch (ServiceSpecificException e) {
                Log.e(TAG, "Failed to tear down chroot", e);
            } catch (IllegalStateException e) {
                // Not expected, but we still want retries in such an extreme case.
                Slog.wtf(TAG, "Unexpected exception", e);
            }

            if (--numRetries > 0) {
                Log.i(TAG, "Retrying....");
                Utils.sleep(30000);
            }
        }
    }

    private void runFromChroot(@NonNull CancellationSignal cancellationSignal)
            throws ReflectiveOperationException {
        String chrootArtDir = CHROOT_DIR + "/apex/com.android.art";
        String dexPath = chrootArtDir + "/javalib/service-art.jar";
        var classLoader =
                new DelegateLastClassLoader(dexPath, this.getClass().getClassLoader() /* parent */);
        Class<?> preRebootManagerClass =
                classLoader.loadClass("com.android.server.art.prereboot.PreRebootManager");
        // Check if the dex file is loaded successfully. Note that the constructor of
        // `DelegateLastClassLoader` does not throw when the load fails.
        if (preRebootManagerClass == PreRebootManager.class) {
            throw new IllegalStateException(String.format("Failed to load %s", dexPath));
        }
        Object preRebootManager = preRebootManagerClass.getConstructor().newInstance();
        preRebootManagerClass
                .getMethod("run", ArtModuleServiceManager.class, Context.class,
                        CancellationSignal.class)
                .invoke(preRebootManager, ArtModuleServiceInitializer.getArtModuleServiceManager(),
                        mInjector.getContext(), cancellationSignal);
    }

    /**
     * Injector pattern for testing purpose.
     *
     * @hide
     */
    @VisibleForTesting
    public static class Injector {
        @NonNull private final Context mContext;

        Injector(@NonNull Context context) {
            mContext = context;
        }

        @NonNull
        public Context getContext() {
            return mContext;
        }

        @NonNull
        public IDexoptChrootSetup getDexoptChrootSetup() {
            return GlobalInjector.getInstance().getDexoptChrootSetup();
        }
    }
}