blob: 90a606d970d985673fb922cbd10ac01d31995a3d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Tom Taylord4a47292009-12-21 13:59:18 -080021import com.android.common.FastXmlSerializer;
22import com.android.common.XmlUtils;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080023import com.android.internal.content.PackageHelper;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080024import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Christopher Tate1bb69062010-02-19 17:02:12 -080032import android.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070037import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080038import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.ActivityInfo;
41import android.content.pm.ApplicationInfo;
42import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070043import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.IPackageDataObserver;
45import android.content.pm.IPackageDeleteObserver;
46import android.content.pm.IPackageInstallObserver;
47import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080048import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.IPackageStatsObserver;
50import android.content.pm.InstrumentationInfo;
51import android.content.pm.PackageInfo;
52import android.content.pm.PackageManager;
53import android.content.pm.PackageStats;
54import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
55import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
57import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
58import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
59import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080081import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080087import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.util.*;
89import android.view.Display;
90import android.view.WindowManager;
91
92import java.io.File;
93import java.io.FileDescriptor;
94import java.io.FileInputStream;
95import java.io.FileNotFoundException;
96import java.io.FileOutputStream;
97import java.io.FileReader;
98import java.io.FilenameFilter;
99import java.io.IOException;
100import java.io.InputStream;
101import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800102import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800103import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.util.ArrayList;
105import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700106import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.Collections;
108import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800109import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Enumeration;
111import java.util.HashMap;
112import java.util.HashSet;
113import java.util.Iterator;
114import java.util.List;
115import java.util.Map;
116import java.util.Set;
117import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800118import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import java.util.zip.ZipFile;
120import java.util.zip.ZipOutputStream;
121
122class PackageManagerService extends IPackageManager.Stub {
123 private static final String TAG = "PackageManager";
124 private static final boolean DEBUG_SETTINGS = false;
125 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800126 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800127 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
129 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
130 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400131 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final int FIRST_APPLICATION_UID =
133 Process.FIRST_APPLICATION_UID;
134 private static final int MAX_APPLICATION_UIDS = 1000;
135
136 private static final boolean SHOW_INFO = false;
137
138 private static final boolean GET_CERTIFICATES = true;
139
Oscar Montemayora8529f62009-11-18 10:14:20 -0800140 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int REMOVE_EVENTS =
143 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
144 private static final int ADD_EVENTS =
145 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
146
147 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800148 // Suffix used during package installation when copying/moving
149 // package apks to install directory.
150 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152 static final int SCAN_MONITOR = 1<<0;
153 static final int SCAN_NO_DEX = 1<<1;
154 static final int SCAN_FORCE_DEX = 1<<2;
155 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800156 static final int SCAN_NEW_INSTALL = 1<<4;
157 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800159 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
160 "com.android.defcontainer",
161 "com.android.defcontainer.DefaultContainerService");
162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
164 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700165 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Dianne Hackborn851a5412009-05-08 12:06:44 -0700167 final int mSdkVersion = Build.VERSION.SDK_INT;
168 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
169 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 final Context mContext;
172 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700173 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 final DisplayMetrics mMetrics;
175 final int mDefParseFlags;
176 final String[] mSeparateProcesses;
177
178 // This is where all application persistent data goes.
179 final File mAppDataDir;
180
Oscar Montemayora8529f62009-11-18 10:14:20 -0800181 // If Encrypted File System feature is enabled, all application persistent data
182 // should go here instead.
183 final File mSecureAppDataDir;
184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 // This is the object monitoring the framework dir.
186 final FileObserver mFrameworkInstallObserver;
187
188 // This is the object monitoring the system app dir.
189 final FileObserver mSystemInstallObserver;
190
191 // This is the object monitoring mAppInstallDir.
192 final FileObserver mAppInstallObserver;
193
194 // This is the object monitoring mDrmAppPrivateInstallDir.
195 final FileObserver mDrmAppInstallObserver;
196
197 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
198 // LOCK HELD. Can be called with mInstallLock held.
199 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final File mFrameworkDir;
202 final File mSystemAppDir;
203 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700204 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
207 // apps.
208 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 // Lock for state used when installing and doing other long running
213 // operations. Methods that must be called with this lock held have
214 // the prefix "LI".
215 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // These are the directories in the 3rd party applications installed dir
218 // that we have currently loaded packages from. Keys are the application's
219 // installed zip file (absolute codePath), and values are Package.
220 final HashMap<String, PackageParser.Package> mAppDirs =
221 new HashMap<String, PackageParser.Package>();
222
223 // Information for the parser to write more useful error messages.
224 File mScanningPath;
225 int mLastScanError;
226
227 final int[] mOutPermissions = new int[3];
228
229 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // Keys are String (package name), values are Package. This also serves
232 // as the lock for the global state. Methods that must be called with
233 // this lock held have the prefix "LP".
234 final HashMap<String, PackageParser.Package> mPackages =
235 new HashMap<String, PackageParser.Package>();
236
237 final Settings mSettings;
238 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
241 int[] mGlobalGids;
242
243 // These are the built-in uid -> permission mappings that were read from the
244 // etc/permissions.xml file.
245 final SparseArray<HashSet<String>> mSystemPermissions =
246 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // These are the built-in shared libraries that were read from the
249 // etc/permissions.xml file.
250 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
Dianne Hackborn49237342009-08-27 20:08:01 -0700252 // Temporary for building the final shared libraries for an .apk.
253 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800254
Dianne Hackborn49237342009-08-27 20:08:01 -0700255 // These are the features this devices supports that were read from the
256 // etc/permissions.xml file.
257 final HashMap<String, FeatureInfo> mAvailableFeatures =
258 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 // All available activities, for your resolving pleasure.
261 final ActivityIntentResolver mActivities =
262 new ActivityIntentResolver();
263
264 // All available receivers, for your resolving pleasure.
265 final ActivityIntentResolver mReceivers =
266 new ActivityIntentResolver();
267
268 // All available services, for your resolving pleasure.
269 final ServiceIntentResolver mServices = new ServiceIntentResolver();
270
271 // Keys are String (provider class name), values are Provider.
272 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
273 new HashMap<ComponentName, PackageParser.Provider>();
274
275 // Mapping from provider base names (first directory in content URI codePath)
276 // to the provider information.
277 final HashMap<String, PackageParser.Provider> mProviders =
278 new HashMap<String, PackageParser.Provider>();
279
280 // Mapping from instrumentation class names to info about them.
281 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
282 new HashMap<ComponentName, PackageParser.Instrumentation>();
283
284 // Mapping from permission names to info about them.
285 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
286 new HashMap<String, PackageParser.PermissionGroup>();
287
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800288 // Packages whose data we have transfered into another package, thus
289 // should no longer exist.
290 final HashSet<String> mTransferedPackages = new HashSet<String>();
291
Dianne Hackborn854060af2009-07-09 18:14:31 -0700292 // Broadcast actions that are only available to the system.
293 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 boolean mSystemReady;
296 boolean mSafeMode;
297 boolean mHasSystemUidErrors;
298
299 ApplicationInfo mAndroidApplication;
300 final ActivityInfo mResolveActivity = new ActivityInfo();
301 final ResolveInfo mResolveInfo = new ResolveInfo();
302 ComponentName mResolveComponentName;
303 PackageParser.Package mPlatformPackage;
304
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700305 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800306 final HashMap<String, ArrayList<String>> mPendingBroadcasts
307 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700308 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800309 static final int MCS_BOUND = 3;
310 static final int END_COPY = 4;
311 static final int INIT_COPY = 5;
312 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800313 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800314 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800315 static final int POST_INSTALL = 9;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700316 // Delay time in millisecs
317 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800318 private ServiceConnection mDefContainerConn = new ServiceConnection() {
319 public void onServiceConnected(ComponentName name, IBinder service) {
320 IMediaContainerService imcs =
321 IMediaContainerService.Stub.asInterface(service);
322 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
323 mHandler.sendMessage(msg);
324 }
325
326 public void onServiceDisconnected(ComponentName name) {
327 }
328 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700329
Christopher Tate1bb69062010-02-19 17:02:12 -0800330 // Recordkeeping of restore-after-install operations that are currently in flight
331 // between the Package Manager and the Backup Manager
332 class PostInstallData {
333 public InstallArgs args;
334 public PackageInstalledInfo res;
335
336 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
337 args = _a;
338 res = _r;
339 }
340 };
341 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
342 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
343
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700344 class PackageHandler extends Handler {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800345 final ArrayList<HandlerParams> mPendingInstalls =
346 new ArrayList<HandlerParams>();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800347 // Service Connection to remote media container service to copy
348 // package uri's from external media onto secure containers
349 // or internal storage.
350 private IMediaContainerService mContainerService = null;
351
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700352 PackageHandler(Looper looper) {
353 super(looper);
354 }
355 public void handleMessage(Message msg) {
356 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800357 case INIT_COPY: {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800358 HandlerParams params = (HandlerParams) msg.obj;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800359 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800360 if (mContainerService != null) {
361 // No need to add to pending list. Use remote stub directly
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800362 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 } else {
364 if (mContext.bindService(service, mDefContainerConn,
365 Context.BIND_AUTO_CREATE)) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800366 mPendingInstalls.add(params);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 } else {
368 Log.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800369 // Indicate service bind error
370 params.handleServiceError();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800371 }
372 }
373 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800374 }
375 case MCS_BOUND: {
376 // Initialize mContainerService if needed.
377 if (msg.obj != null) {
378 mContainerService = (IMediaContainerService) msg.obj;
379 }
380 if (mPendingInstalls.size() > 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800381 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800382 if (params != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800383 params.handleStartCopy(mContainerService);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800384 }
385 }
386 break;
387 }
388 case MCS_UNBIND : {
389 if (mPendingInstalls.size() == 0) {
390 mContext.unbindService(mDefContainerConn);
391 mContainerService = null;
392 }
393 break;
394 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700395 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800396 String packages[];
397 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700398 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700399 int uids[];
400 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800401 if (mPendingBroadcasts == null) {
402 return;
403 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700404 size = mPendingBroadcasts.size();
405 if (size <= 0) {
406 // Nothing to be done. Just return
407 return;
408 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800409 packages = new String[size];
410 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700411 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800412 Iterator<HashMap.Entry<String, ArrayList<String>>>
413 it = mPendingBroadcasts.entrySet().iterator();
414 int i = 0;
415 while (it.hasNext() && i < size) {
416 HashMap.Entry<String, ArrayList<String>> ent = it.next();
417 packages[i] = ent.getKey();
418 components[i] = ent.getValue();
419 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700420 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800421 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700422 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800423 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700424 mPendingBroadcasts.clear();
425 }
426 // Send broadcasts
427 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800428 sendPackageChangedBroadcast(packages[i], true,
429 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 }
431 break;
432 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800433 case START_CLEANING_PACKAGE: {
434 String packageName = (String)msg.obj;
435 synchronized (mPackages) {
436 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
437 mSettings.mPackagesToBeCleaned.add(packageName);
438 }
439 }
440 startCleaningPackages();
441 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800442 case POST_INSTALL: {
443 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
444 PostInstallData data = mRunningInstalls.get(msg.arg1);
445 mRunningInstalls.delete(msg.arg1);
446
447 if (data != null) {
448 InstallArgs args = data.args;
449 PackageInstalledInfo res = data.res;
450
451 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
452 res.removedInfo.sendBroadcast(false, true);
453 Bundle extras = new Bundle(1);
454 extras.putInt(Intent.EXTRA_UID, res.uid);
455 final boolean update = res.removedInfo.removedPackage != null;
456 if (update) {
457 extras.putBoolean(Intent.EXTRA_REPLACING, true);
458 }
459 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
460 res.pkg.applicationInfo.packageName,
461 extras);
462 if (update) {
463 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
464 res.pkg.applicationInfo.packageName,
465 extras);
466 }
467 if (res.removedInfo.args != null) {
468 // Remove the replaced package's older resources safely now
469 synchronized (mInstallLock) {
470 res.removedInfo.args.doPostDeleteLI(true);
471 }
472 }
473 }
474 Runtime.getRuntime().gc();
475
476 if (args.observer != null) {
477 try {
478 args.observer.packageInstalled(res.name, res.returnCode);
479 } catch (RemoteException e) {
480 Log.i(TAG, "Observer no longer exists.");
481 }
482 }
483 } else {
484 Log.e(TAG, "Bogus post-install token " + msg.arg1);
485 }
486 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700487 }
488 }
489 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800490
491 static boolean installOnSd(int flags) {
492 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800493 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800494 return false;
495 }
496 return true;
497 }
498
499 static boolean isFwdLocked(int flags) {
500 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
501 return true;
502 }
503 return false;
504 }
505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 public static final IPackageManager main(Context context, boolean factoryTest) {
507 PackageManagerService m = new PackageManagerService(context, factoryTest);
508 ServiceManager.addService("package", m);
509 return m;
510 }
511
512 static String[] splitString(String str, char sep) {
513 int count = 1;
514 int i = 0;
515 while ((i=str.indexOf(sep, i)) >= 0) {
516 count++;
517 i++;
518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 String[] res = new String[count];
521 i=0;
522 count = 0;
523 int lastI=0;
524 while ((i=str.indexOf(sep, i)) >= 0) {
525 res[count] = str.substring(lastI, i);
526 count++;
527 i++;
528 lastI = i;
529 }
530 res[count] = str.substring(lastI, str.length());
531 return res;
532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800535 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 if (mSdkVersion <= 0) {
539 Log.w(TAG, "**** ro.build.version.sdk not set!");
540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 mContext = context;
543 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700544 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 mMetrics = new DisplayMetrics();
546 mSettings = new Settings();
547 mSettings.addSharedUserLP("android.uid.system",
548 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
549 mSettings.addSharedUserLP("android.uid.phone",
550 MULTIPLE_APPLICATION_UIDS
551 ? RADIO_UID : FIRST_APPLICATION_UID,
552 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400553 mSettings.addSharedUserLP("android.uid.log",
554 MULTIPLE_APPLICATION_UIDS
555 ? LOG_UID : FIRST_APPLICATION_UID,
556 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557
558 String separateProcesses = SystemProperties.get("debug.separate_processes");
559 if (separateProcesses != null && separateProcesses.length() > 0) {
560 if ("*".equals(separateProcesses)) {
561 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
562 mSeparateProcesses = null;
563 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
564 } else {
565 mDefParseFlags = 0;
566 mSeparateProcesses = separateProcesses.split(",");
567 Log.w(TAG, "Running with debug.separate_processes: "
568 + separateProcesses);
569 }
570 } else {
571 mDefParseFlags = 0;
572 mSeparateProcesses = null;
573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 Installer installer = new Installer();
576 // Little hacky thing to check if installd is here, to determine
577 // whether we are running on the simulator and thus need to take
578 // care of building the /data file structure ourself.
579 // (apparently the sim now has a working installer)
580 if (installer.ping() && Process.supportsProcesses()) {
581 mInstaller = installer;
582 } else {
583 mInstaller = null;
584 }
585
586 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
587 Display d = wm.getDefaultDisplay();
588 d.getMetrics(mMetrics);
589
590 synchronized (mInstallLock) {
591 synchronized (mPackages) {
592 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700593 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 File dataDir = Environment.getDataDirectory();
596 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800597 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
599
600 if (mInstaller == null) {
601 // Make sure these dirs exist, when we are running in
602 // the simulator.
603 // Make a wide-open directory for random misc stuff.
604 File miscDir = new File(dataDir, "misc");
605 miscDir.mkdirs();
606 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800607 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 mDrmAppPrivateInstallDir.mkdirs();
609 }
610
611 readPermissions();
612
613 mRestoredSettings = mSettings.readLP();
614 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800615
616 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800618
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800619 // Set flag to monitor and not change apk file paths when
620 // scanning install directories.
621 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700622 if (mNoDexOpt) {
623 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800624 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700630 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700633 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 /**
636 * Out of paranoia, ensure that everything in the boot class
637 * path has been dexed.
638 */
639 String bootClassPath = System.getProperty("java.boot.class.path");
640 if (bootClassPath != null) {
641 String[] paths = splitString(bootClassPath, ':');
642 for (int i=0; i<paths.length; i++) {
643 try {
644 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
645 libFiles.add(paths[i]);
646 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700647 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 }
649 } catch (FileNotFoundException e) {
650 Log.w(TAG, "Boot class path not found: " + paths[i]);
651 } catch (IOException e) {
652 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
653 }
654 }
655 } else {
656 Log.w(TAG, "No BOOTCLASSPATH found!");
657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 /**
660 * Also ensure all external libraries have had dexopt run on them.
661 */
662 if (mSharedLibraries.size() > 0) {
663 Iterator<String> libs = mSharedLibraries.values().iterator();
664 while (libs.hasNext()) {
665 String lib = libs.next();
666 try {
667 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
668 libFiles.add(lib);
669 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700670 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
672 } catch (FileNotFoundException e) {
673 Log.w(TAG, "Library not found: " + lib);
674 } catch (IOException e) {
675 Log.w(TAG, "Exception reading library: " + lib, e);
676 }
677 }
678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 // Gross hack for now: we know this file doesn't contain any
681 // code, so don't dexopt it to avoid the resulting log spew.
682 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 /**
685 * And there are a number of commands implemented in Java, which
686 * we currently need to do the dexopt on so that they can be
687 * run from a non-root shell.
688 */
689 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700690 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 for (int i=0; i<frameworkFiles.length; i++) {
692 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
693 String path = libPath.getPath();
694 // Skip the file if we alrady did it.
695 if (libFiles.contains(path)) {
696 continue;
697 }
698 // Skip the file if it is not a type we want to dexopt.
699 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
700 continue;
701 }
702 try {
703 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
704 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700705 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
707 } catch (FileNotFoundException e) {
708 Log.w(TAG, "Jar not found: " + path);
709 } catch (IOException e) {
710 Log.w(TAG, "Exception reading jar: " + path, e);
711 }
712 }
713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700715 if (didDexOpt) {
716 // If we had to do a dexopt of one of the previous
717 // things, then something on the system has changed.
718 // Consider this significant, and wipe away all other
719 // existing dexopt files to ensure we don't leave any
720 // dangling around.
721 String[] files = mDalvikCacheDir.list();
722 if (files != null) {
723 for (int i=0; i<files.length; i++) {
724 String fn = files[i];
725 if (fn.startsWith("data@app@")
726 || fn.startsWith("data@app-private@")) {
727 Log.i(TAG, "Pruning dalvik file: " + fn);
728 (new File(mDalvikCacheDir, fn)).delete();
729 }
730 }
731 }
732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800734
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800735 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 mFrameworkInstallObserver = new AppDirObserver(
737 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
738 mFrameworkInstallObserver.startWatching();
739 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800740 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800741
742 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
744 mSystemInstallObserver = new AppDirObserver(
745 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
746 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800747 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800748
749 if (mInstaller != null) {
750 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
751 mInstaller.moveFiles();
752 }
753
754 // Prune any system packages that no longer exist.
755 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
756 while (psit.hasNext()) {
757 PackageSetting ps = psit.next();
758 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800759 && !mPackages.containsKey(ps.name)
760 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800761 psit.remove();
762 String msg = "System package " + ps.name
763 + " no longer exists; wiping its data";
764 reportSettingsProblem(Log.WARN, msg);
765 if (mInstaller != null) {
766 // XXX how to set useEncryptedFSDir for packages that
767 // are not encrypted?
768 mInstaller.remove(ps.name, true);
769 }
770 }
771 }
772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 mAppInstallDir = new File(dataDir, "app");
774 if (mInstaller == null) {
775 // Make sure these dirs exist, when we are running in
776 // the simulator.
777 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
778 }
779 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800780 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 //clean up list
782 for(int i = 0; i < deletePkgsList.size(); i++) {
783 //clean up here
784 cleanupInstallFailedPackage(deletePkgsList.get(i));
785 }
786 //delete tmp files
787 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800788
789 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 SystemClock.uptimeMillis());
791 mAppInstallObserver = new AppDirObserver(
792 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
793 mAppInstallObserver.startWatching();
794 scanDirLI(mAppInstallDir, 0, scanMode);
795
796 mDrmAppInstallObserver = new AppDirObserver(
797 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
798 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800799 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 SystemClock.uptimeMillis());
803 Log.i(TAG, "Time to scan packages: "
804 + ((SystemClock.uptimeMillis()-startTime)/1000f)
805 + " seconds");
806
807 updatePermissionsLP();
808
809 mSettings.writeLP();
810
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 // Now after opening every single application zip, make sure they
815 // are all flushed. Not really needed, but keeps things nice and
816 // tidy.
817 Runtime.getRuntime().gc();
818 } // synchronized (mPackages)
819 } // synchronized (mInstallLock)
820 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 @Override
823 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
824 throws RemoteException {
825 try {
826 return super.onTransact(code, data, reply, flags);
827 } catch (RuntimeException e) {
828 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
829 Log.e(TAG, "Package Manager Crash", e);
830 }
831 throw e;
832 }
833 }
834
Dianne Hackborne6620b22010-01-22 14:46:21 -0800835 void cleanupInstallFailedPackage(PackageSetting ps) {
836 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800838 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
839 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 if (retCode < 0) {
841 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800842 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
844 } else {
845 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800846 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 File dataDir = new File(pkg.applicationInfo.dataDir);
848 dataDir.delete();
849 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800850 if (ps.codePath != null) {
851 if (!ps.codePath.delete()) {
852 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
853 }
854 }
855 if (ps.resourcePath != null) {
856 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
857 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
858 }
859 }
860 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862
863 void readPermissions() {
864 // Read permissions from .../etc/permission directory.
865 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
866 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
867 Log.w(TAG, "No directory " + libraryDir + ", skipping");
868 return;
869 }
870 if (!libraryDir.canRead()) {
871 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
872 return;
873 }
874
875 // Iterate over the files in the directory and scan .xml files
876 for (File f : libraryDir.listFiles()) {
877 // We'll read platform.xml last
878 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
879 continue;
880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 if (!f.getPath().endsWith(".xml")) {
883 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
884 continue;
885 }
886 if (!f.canRead()) {
887 Log.w(TAG, "Permissions library file " + f + " cannot be read");
888 continue;
889 }
890
891 readPermissionsFromXml(f);
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
895 final File permFile = new File(Environment.getRootDirectory(),
896 "etc/permissions/platform.xml");
897 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800898
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700899 StringBuilder sb = new StringBuilder(128);
900 sb.append("Libs:");
901 Iterator<String> it = mSharedLibraries.keySet().iterator();
902 while (it.hasNext()) {
903 sb.append(' ');
904 String name = it.next();
905 sb.append(name);
906 sb.append(':');
907 sb.append(mSharedLibraries.get(name));
908 }
909 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800910
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700911 sb.setLength(0);
912 sb.append("Features:");
913 it = mAvailableFeatures.keySet().iterator();
914 while (it.hasNext()) {
915 sb.append(' ');
916 sb.append(it.next());
917 }
918 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800920
921 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 FileReader permReader = null;
923 try {
924 permReader = new FileReader(permFile);
925 } catch (FileNotFoundException e) {
926 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
927 return;
928 }
929
930 try {
931 XmlPullParser parser = Xml.newPullParser();
932 parser.setInput(permReader);
933
934 XmlUtils.beginDocument(parser, "permissions");
935
936 while (true) {
937 XmlUtils.nextElement(parser);
938 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
939 break;
940 }
941
942 String name = parser.getName();
943 if ("group".equals(name)) {
944 String gidStr = parser.getAttributeValue(null, "gid");
945 if (gidStr != null) {
946 int gid = Integer.parseInt(gidStr);
947 mGlobalGids = appendInt(mGlobalGids, gid);
948 } else {
949 Log.w(TAG, "<group> without gid at "
950 + parser.getPositionDescription());
951 }
952
953 XmlUtils.skipCurrentTag(parser);
954 continue;
955 } else if ("permission".equals(name)) {
956 String perm = parser.getAttributeValue(null, "name");
957 if (perm == null) {
958 Log.w(TAG, "<permission> without name at "
959 + parser.getPositionDescription());
960 XmlUtils.skipCurrentTag(parser);
961 continue;
962 }
963 perm = perm.intern();
964 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 } else if ("assign-permission".equals(name)) {
967 String perm = parser.getAttributeValue(null, "name");
968 if (perm == null) {
969 Log.w(TAG, "<assign-permission> without name at "
970 + parser.getPositionDescription());
971 XmlUtils.skipCurrentTag(parser);
972 continue;
973 }
974 String uidStr = parser.getAttributeValue(null, "uid");
975 if (uidStr == null) {
976 Log.w(TAG, "<assign-permission> without uid at "
977 + parser.getPositionDescription());
978 XmlUtils.skipCurrentTag(parser);
979 continue;
980 }
981 int uid = Process.getUidForName(uidStr);
982 if (uid < 0) {
983 Log.w(TAG, "<assign-permission> with unknown uid \""
984 + uidStr + "\" at "
985 + parser.getPositionDescription());
986 XmlUtils.skipCurrentTag(parser);
987 continue;
988 }
989 perm = perm.intern();
990 HashSet<String> perms = mSystemPermissions.get(uid);
991 if (perms == null) {
992 perms = new HashSet<String>();
993 mSystemPermissions.put(uid, perms);
994 }
995 perms.add(perm);
996 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 } else if ("library".equals(name)) {
999 String lname = parser.getAttributeValue(null, "name");
1000 String lfile = parser.getAttributeValue(null, "file");
1001 if (lname == null) {
1002 Log.w(TAG, "<library> without name at "
1003 + parser.getPositionDescription());
1004 } else if (lfile == null) {
1005 Log.w(TAG, "<library> without file at "
1006 + parser.getPositionDescription());
1007 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001008 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001009 mSharedLibraries.put(lname, lfile);
1010 }
1011 XmlUtils.skipCurrentTag(parser);
1012 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001013
Dianne Hackborn49237342009-08-27 20:08:01 -07001014 } else if ("feature".equals(name)) {
1015 String fname = parser.getAttributeValue(null, "name");
1016 if (fname == null) {
1017 Log.w(TAG, "<feature> without name at "
1018 + parser.getPositionDescription());
1019 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001020 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001021 FeatureInfo fi = new FeatureInfo();
1022 fi.name = fname;
1023 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 XmlUtils.skipCurrentTag(parser);
1026 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 } else {
1029 XmlUtils.skipCurrentTag(parser);
1030 continue;
1031 }
1032
1033 }
1034 } catch (XmlPullParserException e) {
1035 Log.w(TAG, "Got execption parsing permissions.", e);
1036 } catch (IOException e) {
1037 Log.w(TAG, "Got execption parsing permissions.", e);
1038 }
1039 }
1040
1041 void readPermission(XmlPullParser parser, String name)
1042 throws IOException, XmlPullParserException {
1043
1044 name = name.intern();
1045
1046 BasePermission bp = mSettings.mPermissions.get(name);
1047 if (bp == null) {
1048 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1049 mSettings.mPermissions.put(name, bp);
1050 }
1051 int outerDepth = parser.getDepth();
1052 int type;
1053 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1054 && (type != XmlPullParser.END_TAG
1055 || parser.getDepth() > outerDepth)) {
1056 if (type == XmlPullParser.END_TAG
1057 || type == XmlPullParser.TEXT) {
1058 continue;
1059 }
1060
1061 String tagName = parser.getName();
1062 if ("group".equals(tagName)) {
1063 String gidStr = parser.getAttributeValue(null, "gid");
1064 if (gidStr != null) {
1065 int gid = Process.getGidForName(gidStr);
1066 bp.gids = appendInt(bp.gids, gid);
1067 } else {
1068 Log.w(TAG, "<group> without gid at "
1069 + parser.getPositionDescription());
1070 }
1071 }
1072 XmlUtils.skipCurrentTag(parser);
1073 }
1074 }
1075
1076 static int[] appendInt(int[] cur, int val) {
1077 if (cur == null) {
1078 return new int[] { val };
1079 }
1080 final int N = cur.length;
1081 for (int i=0; i<N; i++) {
1082 if (cur[i] == val) {
1083 return cur;
1084 }
1085 }
1086 int[] ret = new int[N+1];
1087 System.arraycopy(cur, 0, ret, 0, N);
1088 ret[N] = val;
1089 return ret;
1090 }
1091
1092 static int[] appendInts(int[] cur, int[] add) {
1093 if (add == null) return cur;
1094 if (cur == null) return add;
1095 final int N = add.length;
1096 for (int i=0; i<N; i++) {
1097 cur = appendInt(cur, add[i]);
1098 }
1099 return cur;
1100 }
1101
1102 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001103 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1104 // The package has been uninstalled but has retained data and resources.
1105 return PackageParser.generatePackageInfo(p, null, flags);
1106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 final PackageSetting ps = (PackageSetting)p.mExtras;
1108 if (ps == null) {
1109 return null;
1110 }
1111 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1112 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1113 }
1114
1115 public PackageInfo getPackageInfo(String packageName, int flags) {
1116 synchronized (mPackages) {
1117 PackageParser.Package p = mPackages.get(packageName);
1118 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001119 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 + ": " + p);
1121 if (p != null) {
1122 return generatePackageInfo(p, flags);
1123 }
1124 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1125 return generatePackageInfoFromSettingsLP(packageName, flags);
1126 }
1127 }
1128 return null;
1129 }
1130
Dianne Hackborn47096932010-02-11 15:57:09 -08001131 public String[] currentToCanonicalPackageNames(String[] names) {
1132 String[] out = new String[names.length];
1133 synchronized (mPackages) {
1134 for (int i=names.length-1; i>=0; i--) {
1135 PackageSetting ps = mSettings.mPackages.get(names[i]);
1136 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1137 }
1138 }
1139 return out;
1140 }
1141
1142 public String[] canonicalToCurrentPackageNames(String[] names) {
1143 String[] out = new String[names.length];
1144 synchronized (mPackages) {
1145 for (int i=names.length-1; i>=0; i--) {
1146 String cur = mSettings.mRenamedPackages.get(names[i]);
1147 out[i] = cur != null ? cur : names[i];
1148 }
1149 }
1150 return out;
1151 }
1152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 public int getPackageUid(String packageName) {
1154 synchronized (mPackages) {
1155 PackageParser.Package p = mPackages.get(packageName);
1156 if(p != null) {
1157 return p.applicationInfo.uid;
1158 }
1159 PackageSetting ps = mSettings.mPackages.get(packageName);
1160 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1161 return -1;
1162 }
1163 p = ps.pkg;
1164 return p != null ? p.applicationInfo.uid : -1;
1165 }
1166 }
1167
1168 public int[] getPackageGids(String packageName) {
1169 synchronized (mPackages) {
1170 PackageParser.Package p = mPackages.get(packageName);
1171 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001172 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 + ": " + p);
1174 if (p != null) {
1175 final PackageSetting ps = (PackageSetting)p.mExtras;
1176 final SharedUserSetting suid = ps.sharedUser;
1177 return suid != null ? suid.gids : ps.gids;
1178 }
1179 }
1180 // stupid thing to indicate an error.
1181 return new int[0];
1182 }
1183
1184 public PermissionInfo getPermissionInfo(String name, int flags) {
1185 synchronized (mPackages) {
1186 final BasePermission p = mSettings.mPermissions.get(name);
1187 if (p != null && p.perm != null) {
1188 return PackageParser.generatePermissionInfo(p.perm, flags);
1189 }
1190 return null;
1191 }
1192 }
1193
1194 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1195 synchronized (mPackages) {
1196 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1197 for (BasePermission p : mSettings.mPermissions.values()) {
1198 if (group == null) {
1199 if (p.perm.info.group == null) {
1200 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1201 }
1202 } else {
1203 if (group.equals(p.perm.info.group)) {
1204 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1205 }
1206 }
1207 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 if (out.size() > 0) {
1210 return out;
1211 }
1212 return mPermissionGroups.containsKey(group) ? out : null;
1213 }
1214 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1217 synchronized (mPackages) {
1218 return PackageParser.generatePermissionGroupInfo(
1219 mPermissionGroups.get(name), flags);
1220 }
1221 }
1222
1223 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1224 synchronized (mPackages) {
1225 final int N = mPermissionGroups.size();
1226 ArrayList<PermissionGroupInfo> out
1227 = new ArrayList<PermissionGroupInfo>(N);
1228 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1229 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1230 }
1231 return out;
1232 }
1233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1236 PackageSetting ps = mSettings.mPackages.get(packageName);
1237 if(ps != null) {
1238 if(ps.pkg == null) {
1239 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1240 if(pInfo != null) {
1241 return pInfo.applicationInfo;
1242 }
1243 return null;
1244 }
1245 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1246 }
1247 return null;
1248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1251 PackageSetting ps = mSettings.mPackages.get(packageName);
1252 if(ps != null) {
1253 if(ps.pkg == null) {
1254 ps.pkg = new PackageParser.Package(packageName);
1255 ps.pkg.applicationInfo.packageName = packageName;
1256 }
1257 return generatePackageInfo(ps.pkg, flags);
1258 }
1259 return null;
1260 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1263 synchronized (mPackages) {
1264 PackageParser.Package p = mPackages.get(packageName);
1265 if (Config.LOGV) Log.v(
1266 TAG, "getApplicationInfo " + packageName
1267 + ": " + p);
1268 if (p != null) {
1269 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001270 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 }
1272 if ("android".equals(packageName)||"system".equals(packageName)) {
1273 return mAndroidApplication;
1274 }
1275 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1276 return generateApplicationInfoFromSettingsLP(packageName, flags);
1277 }
1278 }
1279 return null;
1280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001281
1282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1284 mContext.enforceCallingOrSelfPermission(
1285 android.Manifest.permission.CLEAR_APP_CACHE, null);
1286 // Queue up an async operation since clearing cache may take a little while.
1287 mHandler.post(new Runnable() {
1288 public void run() {
1289 mHandler.removeCallbacks(this);
1290 int retCode = -1;
1291 if (mInstaller != null) {
1292 retCode = mInstaller.freeCache(freeStorageSize);
1293 if (retCode < 0) {
1294 Log.w(TAG, "Couldn't clear application caches");
1295 }
1296 } //end if mInstaller
1297 if (observer != null) {
1298 try {
1299 observer.onRemoveCompleted(null, (retCode >= 0));
1300 } catch (RemoteException e) {
1301 Log.w(TAG, "RemoveException when invoking call back");
1302 }
1303 }
1304 }
1305 });
1306 }
1307
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001308 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001309 mContext.enforceCallingOrSelfPermission(
1310 android.Manifest.permission.CLEAR_APP_CACHE, null);
1311 // Queue up an async operation since clearing cache may take a little while.
1312 mHandler.post(new Runnable() {
1313 public void run() {
1314 mHandler.removeCallbacks(this);
1315 int retCode = -1;
1316 if (mInstaller != null) {
1317 retCode = mInstaller.freeCache(freeStorageSize);
1318 if (retCode < 0) {
1319 Log.w(TAG, "Couldn't clear application caches");
1320 }
1321 }
1322 if(pi != null) {
1323 try {
1324 // Callback via pending intent
1325 int code = (retCode >= 0) ? 1 : 0;
1326 pi.sendIntent(null, code, null,
1327 null, null);
1328 } catch (SendIntentException e1) {
1329 Log.i(TAG, "Failed to send pending intent");
1330 }
1331 }
1332 }
1333 });
1334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1337 synchronized (mPackages) {
1338 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001339
1340 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001342 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
1344 if (mResolveComponentName.equals(component)) {
1345 return mResolveActivity;
1346 }
1347 }
1348 return null;
1349 }
1350
1351 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1352 synchronized (mPackages) {
1353 PackageParser.Activity a = mReceivers.mActivities.get(component);
1354 if (Config.LOGV) Log.v(
1355 TAG, "getReceiverInfo " + component + ": " + a);
1356 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1357 return PackageParser.generateActivityInfo(a, flags);
1358 }
1359 }
1360 return null;
1361 }
1362
1363 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1364 synchronized (mPackages) {
1365 PackageParser.Service s = mServices.mServices.get(component);
1366 if (Config.LOGV) Log.v(
1367 TAG, "getServiceInfo " + component + ": " + s);
1368 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1369 return PackageParser.generateServiceInfo(s, flags);
1370 }
1371 }
1372 return null;
1373 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 public String[] getSystemSharedLibraryNames() {
1376 Set<String> libSet;
1377 synchronized (mPackages) {
1378 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001379 int size = libSet.size();
1380 if (size > 0) {
1381 String[] libs = new String[size];
1382 libSet.toArray(libs);
1383 return libs;
1384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001386 return null;
1387 }
1388
1389 public FeatureInfo[] getSystemAvailableFeatures() {
1390 Collection<FeatureInfo> featSet;
1391 synchronized (mPackages) {
1392 featSet = mAvailableFeatures.values();
1393 int size = featSet.size();
1394 if (size > 0) {
1395 FeatureInfo[] features = new FeatureInfo[size+1];
1396 featSet.toArray(features);
1397 FeatureInfo fi = new FeatureInfo();
1398 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1399 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1400 features[size] = fi;
1401 return features;
1402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 return null;
1405 }
1406
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001407 public boolean hasSystemFeature(String name) {
1408 synchronized (mPackages) {
1409 return mAvailableFeatures.containsKey(name);
1410 }
1411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 public int checkPermission(String permName, String pkgName) {
1414 synchronized (mPackages) {
1415 PackageParser.Package p = mPackages.get(pkgName);
1416 if (p != null && p.mExtras != null) {
1417 PackageSetting ps = (PackageSetting)p.mExtras;
1418 if (ps.sharedUser != null) {
1419 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1420 return PackageManager.PERMISSION_GRANTED;
1421 }
1422 } else if (ps.grantedPermissions.contains(permName)) {
1423 return PackageManager.PERMISSION_GRANTED;
1424 }
1425 }
1426 }
1427 return PackageManager.PERMISSION_DENIED;
1428 }
1429
1430 public int checkUidPermission(String permName, int uid) {
1431 synchronized (mPackages) {
1432 Object obj = mSettings.getUserIdLP(uid);
1433 if (obj != null) {
1434 if (obj instanceof SharedUserSetting) {
1435 SharedUserSetting sus = (SharedUserSetting)obj;
1436 if (sus.grantedPermissions.contains(permName)) {
1437 return PackageManager.PERMISSION_GRANTED;
1438 }
1439 } else if (obj instanceof PackageSetting) {
1440 PackageSetting ps = (PackageSetting)obj;
1441 if (ps.grantedPermissions.contains(permName)) {
1442 return PackageManager.PERMISSION_GRANTED;
1443 }
1444 }
1445 } else {
1446 HashSet<String> perms = mSystemPermissions.get(uid);
1447 if (perms != null && perms.contains(permName)) {
1448 return PackageManager.PERMISSION_GRANTED;
1449 }
1450 }
1451 }
1452 return PackageManager.PERMISSION_DENIED;
1453 }
1454
1455 private BasePermission findPermissionTreeLP(String permName) {
1456 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1457 if (permName.startsWith(bp.name) &&
1458 permName.length() > bp.name.length() &&
1459 permName.charAt(bp.name.length()) == '.') {
1460 return bp;
1461 }
1462 }
1463 return null;
1464 }
1465
1466 private BasePermission checkPermissionTreeLP(String permName) {
1467 if (permName != null) {
1468 BasePermission bp = findPermissionTreeLP(permName);
1469 if (bp != null) {
1470 if (bp.uid == Binder.getCallingUid()) {
1471 return bp;
1472 }
1473 throw new SecurityException("Calling uid "
1474 + Binder.getCallingUid()
1475 + " is not allowed to add to permission tree "
1476 + bp.name + " owned by uid " + bp.uid);
1477 }
1478 }
1479 throw new SecurityException("No permission tree found for " + permName);
1480 }
1481
1482 public boolean addPermission(PermissionInfo info) {
1483 synchronized (mPackages) {
1484 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1485 throw new SecurityException("Label must be specified in permission");
1486 }
1487 BasePermission tree = checkPermissionTreeLP(info.name);
1488 BasePermission bp = mSettings.mPermissions.get(info.name);
1489 boolean added = bp == null;
1490 if (added) {
1491 bp = new BasePermission(info.name, tree.sourcePackage,
1492 BasePermission.TYPE_DYNAMIC);
1493 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1494 throw new SecurityException(
1495 "Not allowed to modify non-dynamic permission "
1496 + info.name);
1497 }
1498 bp.perm = new PackageParser.Permission(tree.perm.owner,
1499 new PermissionInfo(info));
1500 bp.perm.info.packageName = tree.perm.info.packageName;
1501 bp.uid = tree.uid;
1502 if (added) {
1503 mSettings.mPermissions.put(info.name, bp);
1504 }
1505 mSettings.writeLP();
1506 return added;
1507 }
1508 }
1509
1510 public void removePermission(String name) {
1511 synchronized (mPackages) {
1512 checkPermissionTreeLP(name);
1513 BasePermission bp = mSettings.mPermissions.get(name);
1514 if (bp != null) {
1515 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1516 throw new SecurityException(
1517 "Not allowed to modify non-dynamic permission "
1518 + name);
1519 }
1520 mSettings.mPermissions.remove(name);
1521 mSettings.writeLP();
1522 }
1523 }
1524 }
1525
Dianne Hackborn854060af2009-07-09 18:14:31 -07001526 public boolean isProtectedBroadcast(String actionName) {
1527 synchronized (mPackages) {
1528 return mProtectedBroadcasts.contains(actionName);
1529 }
1530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 public int checkSignatures(String pkg1, String pkg2) {
1533 synchronized (mPackages) {
1534 PackageParser.Package p1 = mPackages.get(pkg1);
1535 PackageParser.Package p2 = mPackages.get(pkg2);
1536 if (p1 == null || p1.mExtras == null
1537 || p2 == null || p2.mExtras == null) {
1538 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1539 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001540 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001544 public int checkUidSignatures(int uid1, int uid2) {
1545 synchronized (mPackages) {
1546 Signature[] s1;
1547 Signature[] s2;
1548 Object obj = mSettings.getUserIdLP(uid1);
1549 if (obj != null) {
1550 if (obj instanceof SharedUserSetting) {
1551 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1552 } else if (obj instanceof PackageSetting) {
1553 s1 = ((PackageSetting)obj).signatures.mSignatures;
1554 } else {
1555 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1556 }
1557 } else {
1558 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1559 }
1560 obj = mSettings.getUserIdLP(uid2);
1561 if (obj != null) {
1562 if (obj instanceof SharedUserSetting) {
1563 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1564 } else if (obj instanceof PackageSetting) {
1565 s2 = ((PackageSetting)obj).signatures.mSignatures;
1566 } else {
1567 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1568 }
1569 } else {
1570 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1571 }
1572 return checkSignaturesLP(s1, s2);
1573 }
1574 }
1575
1576 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1577 if (s1 == null) {
1578 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1580 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1581 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001582 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1584 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001585 final int N1 = s1.length;
1586 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 for (int i=0; i<N1; i++) {
1588 boolean match = false;
1589 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001590 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 match = true;
1592 break;
1593 }
1594 }
1595 if (!match) {
1596 return PackageManager.SIGNATURE_NO_MATCH;
1597 }
1598 }
1599 return PackageManager.SIGNATURE_MATCH;
1600 }
1601
1602 public String[] getPackagesForUid(int uid) {
1603 synchronized (mPackages) {
1604 Object obj = mSettings.getUserIdLP(uid);
1605 if (obj instanceof SharedUserSetting) {
1606 SharedUserSetting sus = (SharedUserSetting)obj;
1607 final int N = sus.packages.size();
1608 String[] res = new String[N];
1609 Iterator<PackageSetting> it = sus.packages.iterator();
1610 int i=0;
1611 while (it.hasNext()) {
1612 res[i++] = it.next().name;
1613 }
1614 return res;
1615 } else if (obj instanceof PackageSetting) {
1616 PackageSetting ps = (PackageSetting)obj;
1617 return new String[] { ps.name };
1618 }
1619 }
1620 return null;
1621 }
1622
1623 public String getNameForUid(int uid) {
1624 synchronized (mPackages) {
1625 Object obj = mSettings.getUserIdLP(uid);
1626 if (obj instanceof SharedUserSetting) {
1627 SharedUserSetting sus = (SharedUserSetting)obj;
1628 return sus.name + ":" + sus.userId;
1629 } else if (obj instanceof PackageSetting) {
1630 PackageSetting ps = (PackageSetting)obj;
1631 return ps.name;
1632 }
1633 }
1634 return null;
1635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 public int getUidForSharedUser(String sharedUserName) {
1638 if(sharedUserName == null) {
1639 return -1;
1640 }
1641 synchronized (mPackages) {
1642 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1643 if(suid == null) {
1644 return -1;
1645 }
1646 return suid.userId;
1647 }
1648 }
1649
1650 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1651 int flags) {
1652 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001653 return chooseBestActivity(intent, resolvedType, flags, query);
1654 }
1655
Mihai Predaeae850c2009-05-13 10:13:48 +02001656 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1657 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (query != null) {
1659 final int N = query.size();
1660 if (N == 1) {
1661 return query.get(0);
1662 } else if (N > 1) {
1663 // If there is more than one activity with the same priority,
1664 // then let the user decide between them.
1665 ResolveInfo r0 = query.get(0);
1666 ResolveInfo r1 = query.get(1);
1667 if (false) {
1668 System.out.println(r0.activityInfo.name +
1669 "=" + r0.priority + " vs " +
1670 r1.activityInfo.name +
1671 "=" + r1.priority);
1672 }
1673 // If the first activity has a higher priority, or a different
1674 // default, then it is always desireable to pick it.
1675 if (r0.priority != r1.priority
1676 || r0.preferredOrder != r1.preferredOrder
1677 || r0.isDefault != r1.isDefault) {
1678 return query.get(0);
1679 }
1680 // If we have saved a preference for a preferred activity for
1681 // this Intent, use that.
1682 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1683 flags, query, r0.priority);
1684 if (ri != null) {
1685 return ri;
1686 }
1687 return mResolveInfo;
1688 }
1689 }
1690 return null;
1691 }
1692
1693 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1694 int flags, List<ResolveInfo> query, int priority) {
1695 synchronized (mPackages) {
1696 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1697 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001698 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1700 if (prefs != null && prefs.size() > 0) {
1701 // First figure out how good the original match set is.
1702 // We will only allow preferred activities that came
1703 // from the same match quality.
1704 int match = 0;
1705 final int N = query.size();
1706 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1707 for (int j=0; j<N; j++) {
1708 ResolveInfo ri = query.get(j);
1709 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1710 + ": 0x" + Integer.toHexString(match));
1711 if (ri.match > match) match = ri.match;
1712 }
1713 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1714 + Integer.toHexString(match));
1715 match &= IntentFilter.MATCH_CATEGORY_MASK;
1716 final int M = prefs.size();
1717 for (int i=0; i<M; i++) {
1718 PreferredActivity pa = prefs.get(i);
1719 if (pa.mMatch != match) {
1720 continue;
1721 }
1722 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1723 if (DEBUG_PREFERRED) {
1724 Log.v(TAG, "Got preferred activity:");
1725 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1726 }
1727 if (ai != null) {
1728 for (int j=0; j<N; j++) {
1729 ResolveInfo ri = query.get(j);
1730 if (!ri.activityInfo.applicationInfo.packageName
1731 .equals(ai.applicationInfo.packageName)) {
1732 continue;
1733 }
1734 if (!ri.activityInfo.name.equals(ai.name)) {
1735 continue;
1736 }
1737
1738 // Okay we found a previously set preferred app.
1739 // If the result set is different from when this
1740 // was created, we need to clear it and re-ask the
1741 // user their preference.
1742 if (!pa.sameSet(query, priority)) {
1743 Log.i(TAG, "Result set changed, dropping preferred activity for "
1744 + intent + " type " + resolvedType);
1745 mSettings.mPreferredActivities.removeFilter(pa);
1746 return null;
1747 }
1748
1749 // Yay!
1750 return ri;
1751 }
1752 }
1753 }
1754 }
1755 }
1756 return null;
1757 }
1758
1759 public List<ResolveInfo> queryIntentActivities(Intent intent,
1760 String resolvedType, int flags) {
1761 ComponentName comp = intent.getComponent();
1762 if (comp != null) {
1763 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1764 ActivityInfo ai = getActivityInfo(comp, flags);
1765 if (ai != null) {
1766 ResolveInfo ri = new ResolveInfo();
1767 ri.activityInfo = ai;
1768 list.add(ri);
1769 }
1770 return list;
1771 }
1772
1773 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001774 String pkgName = intent.getPackage();
1775 if (pkgName == null) {
1776 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1777 resolvedType, flags);
1778 }
1779 PackageParser.Package pkg = mPackages.get(pkgName);
1780 if (pkg != null) {
1781 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1782 resolvedType, flags, pkg.activities);
1783 }
1784 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 }
1786 }
1787
1788 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1789 Intent[] specifics, String[] specificTypes, Intent intent,
1790 String resolvedType, int flags) {
1791 final String resultsAction = intent.getAction();
1792
1793 List<ResolveInfo> results = queryIntentActivities(
1794 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1795 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1796
1797 int specificsPos = 0;
1798 int N;
1799
1800 // todo: note that the algorithm used here is O(N^2). This
1801 // isn't a problem in our current environment, but if we start running
1802 // into situations where we have more than 5 or 10 matches then this
1803 // should probably be changed to something smarter...
1804
1805 // First we go through and resolve each of the specific items
1806 // that were supplied, taking care of removing any corresponding
1807 // duplicate items in the generic resolve list.
1808 if (specifics != null) {
1809 for (int i=0; i<specifics.length; i++) {
1810 final Intent sintent = specifics[i];
1811 if (sintent == null) {
1812 continue;
1813 }
1814
1815 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1816 String action = sintent.getAction();
1817 if (resultsAction != null && resultsAction.equals(action)) {
1818 // If this action was explicitly requested, then don't
1819 // remove things that have it.
1820 action = null;
1821 }
1822 ComponentName comp = sintent.getComponent();
1823 ResolveInfo ri = null;
1824 ActivityInfo ai = null;
1825 if (comp == null) {
1826 ri = resolveIntent(
1827 sintent,
1828 specificTypes != null ? specificTypes[i] : null,
1829 flags);
1830 if (ri == null) {
1831 continue;
1832 }
1833 if (ri == mResolveInfo) {
1834 // ACK! Must do something better with this.
1835 }
1836 ai = ri.activityInfo;
1837 comp = new ComponentName(ai.applicationInfo.packageName,
1838 ai.name);
1839 } else {
1840 ai = getActivityInfo(comp, flags);
1841 if (ai == null) {
1842 continue;
1843 }
1844 }
1845
1846 // Look for any generic query activities that are duplicates
1847 // of this specific one, and remove them from the results.
1848 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1849 N = results.size();
1850 int j;
1851 for (j=specificsPos; j<N; j++) {
1852 ResolveInfo sri = results.get(j);
1853 if ((sri.activityInfo.name.equals(comp.getClassName())
1854 && sri.activityInfo.applicationInfo.packageName.equals(
1855 comp.getPackageName()))
1856 || (action != null && sri.filter.matchAction(action))) {
1857 results.remove(j);
1858 if (Config.LOGV) Log.v(
1859 TAG, "Removing duplicate item from " + j
1860 + " due to specific " + specificsPos);
1861 if (ri == null) {
1862 ri = sri;
1863 }
1864 j--;
1865 N--;
1866 }
1867 }
1868
1869 // Add this specific item to its proper place.
1870 if (ri == null) {
1871 ri = new ResolveInfo();
1872 ri.activityInfo = ai;
1873 }
1874 results.add(specificsPos, ri);
1875 ri.specificIndex = i;
1876 specificsPos++;
1877 }
1878 }
1879
1880 // Now we go through the remaining generic results and remove any
1881 // duplicate actions that are found here.
1882 N = results.size();
1883 for (int i=specificsPos; i<N-1; i++) {
1884 final ResolveInfo rii = results.get(i);
1885 if (rii.filter == null) {
1886 continue;
1887 }
1888
1889 // Iterate over all of the actions of this result's intent
1890 // filter... typically this should be just one.
1891 final Iterator<String> it = rii.filter.actionsIterator();
1892 if (it == null) {
1893 continue;
1894 }
1895 while (it.hasNext()) {
1896 final String action = it.next();
1897 if (resultsAction != null && resultsAction.equals(action)) {
1898 // If this action was explicitly requested, then don't
1899 // remove things that have it.
1900 continue;
1901 }
1902 for (int j=i+1; j<N; j++) {
1903 final ResolveInfo rij = results.get(j);
1904 if (rij.filter != null && rij.filter.hasAction(action)) {
1905 results.remove(j);
1906 if (Config.LOGV) Log.v(
1907 TAG, "Removing duplicate item from " + j
1908 + " due to action " + action + " at " + i);
1909 j--;
1910 N--;
1911 }
1912 }
1913 }
1914
1915 // If the caller didn't request filter information, drop it now
1916 // so we don't have to marshall/unmarshall it.
1917 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1918 rii.filter = null;
1919 }
1920 }
1921
1922 // Filter out the caller activity if so requested.
1923 if (caller != null) {
1924 N = results.size();
1925 for (int i=0; i<N; i++) {
1926 ActivityInfo ainfo = results.get(i).activityInfo;
1927 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1928 && caller.getClassName().equals(ainfo.name)) {
1929 results.remove(i);
1930 break;
1931 }
1932 }
1933 }
1934
1935 // If the caller didn't request filter information,
1936 // drop them now so we don't have to
1937 // marshall/unmarshall it.
1938 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1939 N = results.size();
1940 for (int i=0; i<N; i++) {
1941 results.get(i).filter = null;
1942 }
1943 }
1944
1945 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1946 return results;
1947 }
1948
1949 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1950 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001951 ComponentName comp = intent.getComponent();
1952 if (comp != null) {
1953 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1954 ActivityInfo ai = getReceiverInfo(comp, flags);
1955 if (ai != null) {
1956 ResolveInfo ri = new ResolveInfo();
1957 ri.activityInfo = ai;
1958 list.add(ri);
1959 }
1960 return list;
1961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001964 String pkgName = intent.getPackage();
1965 if (pkgName == null) {
1966 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1967 resolvedType, flags);
1968 }
1969 PackageParser.Package pkg = mPackages.get(pkgName);
1970 if (pkg != null) {
1971 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1972 resolvedType, flags, pkg.receivers);
1973 }
1974 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
1976 }
1977
1978 public ResolveInfo resolveService(Intent intent, String resolvedType,
1979 int flags) {
1980 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1981 flags);
1982 if (query != null) {
1983 if (query.size() >= 1) {
1984 // If there is more than one service with the same priority,
1985 // just arbitrarily pick the first one.
1986 return query.get(0);
1987 }
1988 }
1989 return null;
1990 }
1991
1992 public List<ResolveInfo> queryIntentServices(Intent intent,
1993 String resolvedType, int flags) {
1994 ComponentName comp = intent.getComponent();
1995 if (comp != null) {
1996 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1997 ServiceInfo si = getServiceInfo(comp, flags);
1998 if (si != null) {
1999 ResolveInfo ri = new ResolveInfo();
2000 ri.serviceInfo = si;
2001 list.add(ri);
2002 }
2003 return list;
2004 }
2005
2006 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002007 String pkgName = intent.getPackage();
2008 if (pkgName == null) {
2009 return (List<ResolveInfo>)mServices.queryIntent(intent,
2010 resolvedType, flags);
2011 }
2012 PackageParser.Package pkg = mPackages.get(pkgName);
2013 if (pkg != null) {
2014 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2015 resolvedType, flags, pkg.services);
2016 }
2017 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 }
2019 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 public List<PackageInfo> getInstalledPackages(int flags) {
2022 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2023
2024 synchronized (mPackages) {
2025 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2026 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2027 while (i.hasNext()) {
2028 final PackageSetting ps = i.next();
2029 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2030 if(psPkg != null) {
2031 finalList.add(psPkg);
2032 }
2033 }
2034 }
2035 else {
2036 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2037 while (i.hasNext()) {
2038 final PackageParser.Package p = i.next();
2039 if (p.applicationInfo != null) {
2040 PackageInfo pi = generatePackageInfo(p, flags);
2041 if(pi != null) {
2042 finalList.add(pi);
2043 }
2044 }
2045 }
2046 }
2047 }
2048 return finalList;
2049 }
2050
2051 public List<ApplicationInfo> getInstalledApplications(int flags) {
2052 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2053 synchronized(mPackages) {
2054 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2055 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2056 while (i.hasNext()) {
2057 final PackageSetting ps = i.next();
2058 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2059 if(ai != null) {
2060 finalList.add(ai);
2061 }
2062 }
2063 }
2064 else {
2065 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2066 while (i.hasNext()) {
2067 final PackageParser.Package p = i.next();
2068 if (p.applicationInfo != null) {
2069 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2070 if(ai != null) {
2071 finalList.add(ai);
2072 }
2073 }
2074 }
2075 }
2076 }
2077 return finalList;
2078 }
2079
2080 public List<ApplicationInfo> getPersistentApplications(int flags) {
2081 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2082
2083 synchronized (mPackages) {
2084 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2085 while (i.hasNext()) {
2086 PackageParser.Package p = i.next();
2087 if (p.applicationInfo != null
2088 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2089 && (!mSafeMode || (p.applicationInfo.flags
2090 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2091 finalList.add(p.applicationInfo);
2092 }
2093 }
2094 }
2095
2096 return finalList;
2097 }
2098
2099 public ProviderInfo resolveContentProvider(String name, int flags) {
2100 synchronized (mPackages) {
2101 final PackageParser.Provider provider = mProviders.get(name);
2102 return provider != null
2103 && mSettings.isEnabledLP(provider.info, flags)
2104 && (!mSafeMode || (provider.info.applicationInfo.flags
2105 &ApplicationInfo.FLAG_SYSTEM) != 0)
2106 ? PackageParser.generateProviderInfo(provider, flags)
2107 : null;
2108 }
2109 }
2110
Fred Quintana718d8a22009-04-29 17:53:20 -07002111 /**
2112 * @deprecated
2113 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 public void querySyncProviders(List outNames, List outInfo) {
2115 synchronized (mPackages) {
2116 Iterator<Map.Entry<String, PackageParser.Provider>> i
2117 = mProviders.entrySet().iterator();
2118
2119 while (i.hasNext()) {
2120 Map.Entry<String, PackageParser.Provider> entry = i.next();
2121 PackageParser.Provider p = entry.getValue();
2122
2123 if (p.syncable
2124 && (!mSafeMode || (p.info.applicationInfo.flags
2125 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2126 outNames.add(entry.getKey());
2127 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2128 }
2129 }
2130 }
2131 }
2132
2133 public List<ProviderInfo> queryContentProviders(String processName,
2134 int uid, int flags) {
2135 ArrayList<ProviderInfo> finalList = null;
2136
2137 synchronized (mPackages) {
2138 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2139 while (i.hasNext()) {
2140 PackageParser.Provider p = i.next();
2141 if (p.info.authority != null
2142 && (processName == null ||
2143 (p.info.processName.equals(processName)
2144 && p.info.applicationInfo.uid == uid))
2145 && mSettings.isEnabledLP(p.info, flags)
2146 && (!mSafeMode || (p.info.applicationInfo.flags
2147 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2148 if (finalList == null) {
2149 finalList = new ArrayList<ProviderInfo>(3);
2150 }
2151 finalList.add(PackageParser.generateProviderInfo(p,
2152 flags));
2153 }
2154 }
2155 }
2156
2157 if (finalList != null) {
2158 Collections.sort(finalList, mProviderInitOrderSorter);
2159 }
2160
2161 return finalList;
2162 }
2163
2164 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2165 int flags) {
2166 synchronized (mPackages) {
2167 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2168 return PackageParser.generateInstrumentationInfo(i, flags);
2169 }
2170 }
2171
2172 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2173 int flags) {
2174 ArrayList<InstrumentationInfo> finalList =
2175 new ArrayList<InstrumentationInfo>();
2176
2177 synchronized (mPackages) {
2178 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2179 while (i.hasNext()) {
2180 PackageParser.Instrumentation p = i.next();
2181 if (targetPackage == null
2182 || targetPackage.equals(p.info.targetPackage)) {
2183 finalList.add(PackageParser.generateInstrumentationInfo(p,
2184 flags));
2185 }
2186 }
2187 }
2188
2189 return finalList;
2190 }
2191
2192 private void scanDirLI(File dir, int flags, int scanMode) {
2193 Log.d(TAG, "Scanning app dir " + dir);
2194
2195 String[] files = dir.list();
2196
2197 int i;
2198 for (i=0; i<files.length; i++) {
2199 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002200 if (!isPackageFilename(files[i])) {
2201 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002202 continue;
2203 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002204 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002206 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002207 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2208 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002209 // Delete the apk
2210 Log.w(TAG, "Cleaning up failed install of " + file);
2211 file.delete();
2212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 }
2214 }
2215
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002216 private static File getSettingsProblemFile() {
2217 File dataDir = Environment.getDataDirectory();
2218 File systemDir = new File(dataDir, "system");
2219 File fname = new File(systemDir, "uiderrors.txt");
2220 return fname;
2221 }
2222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 private static void reportSettingsProblem(int priority, String msg) {
2224 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002225 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 FileOutputStream out = new FileOutputStream(fname, true);
2227 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002228 SimpleDateFormat formatter = new SimpleDateFormat();
2229 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2230 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 pw.close();
2232 FileUtils.setPermissions(
2233 fname.toString(),
2234 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2235 -1, -1);
2236 } catch (java.io.IOException e) {
2237 }
2238 Log.println(priority, TAG, msg);
2239 }
2240
2241 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2242 PackageParser.Package pkg, File srcFile, int parseFlags) {
2243 if (GET_CERTIFICATES) {
2244 if (ps == null || !ps.codePath.equals(srcFile)
2245 || ps.getTimeStamp() != srcFile.lastModified()) {
2246 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2247 if (!pp.collectCertificates(pkg, parseFlags)) {
2248 mLastScanError = pp.getParseError();
2249 return false;
2250 }
2251 }
2252 }
2253 return true;
2254 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 /*
2257 * Scan a package and return the newly parsed package.
2258 * Returns null in case of errors and the error code is stored in mLastScanError
2259 */
2260 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002261 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002263 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002265 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002268 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 if (pkg == null) {
2270 mLastScanError = pp.getParseError();
2271 return null;
2272 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002273 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 PackageSetting updatedPkg;
2275 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002276 // Look to see if we already know about this package.
2277 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
2278 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2279 // This package has been renamed to its original name. Let's
2280 // use that.
2281 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2282 }
2283 // If there was no original package, see one for the real package name.
2284 if (ps == null) {
2285 ps = mSettings.peekPackageLP(pkg.packageName);
2286 }
2287 // Check to see if this package could be hiding/updating a system
2288 // package. Must look for it either under the original or real
2289 // package name depending on our state.
2290 updatedPkg = mSettings.mDisabledSysPackages.get(
2291 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002293 // First check if this is a system package that may involve an update
2294 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2295 if (!ps.codePath.equals(scanFile)) {
2296 // The path has changed from what was last scanned... check the
2297 // version of the new path against what we have stored to determine
2298 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002299 if (pkg.mVersionCode < ps.versionCode) {
2300 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002301 // Ignore entry. Skip it.
2302 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2303 + "ignored: updated version " + ps.versionCode
2304 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002305 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2306 return null;
2307 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002308 // The current app on the system partion is better than
2309 // what we have updated to on the data partition; switch
2310 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002311 // At this point, its safely assumed that package installation for
2312 // apps in system partition will go through. If not there won't be a working
2313 // version of the app
2314 synchronized (mPackages) {
2315 // Just remove the loaded entries from package lists.
2316 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002317 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002318 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2319 + "reverting from " + ps.codePathString
2320 + ": new version " + pkg.mVersionCode
2321 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002322 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2323 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002324 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 }
2327 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002328 if (updatedPkg != null) {
2329 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2330 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2331 }
2332 // Verify certificates against what was last scanned
2333 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2334 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2335 return null;
2336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 // The apk is forward locked (not public) if its code and resources
2338 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002339 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002341 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002342 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002343
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002344 String codePath = null;
2345 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002346 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2347 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002348 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002349 } else {
2350 // Should not happen at all. Just log an error.
2351 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2352 }
2353 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002354 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002355 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002356 codePath = pkg.mScanPath;
2357 // Set application objects path explicitly.
2358 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002360 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 }
2362
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002363 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2364 String destCodePath, String destResPath) {
2365 pkg.mPath = pkg.mScanPath = destCodePath;
2366 pkg.applicationInfo.sourceDir = destCodePath;
2367 pkg.applicationInfo.publicSourceDir = destResPath;
2368 }
2369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 private static String fixProcessName(String defProcessName,
2371 String processName, int uid) {
2372 if (processName == null) {
2373 return defProcessName;
2374 }
2375 return processName;
2376 }
2377
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002378 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2380 if (pkg.mSignatures != null) {
2381 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2382 updateSignature)) {
2383 Log.e(TAG, "Package " + pkg.packageName
2384 + " signatures do not match the previously installed version; ignoring!");
2385 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2386 return false;
2387 }
2388
2389 if (pkgSetting.sharedUser != null) {
2390 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2391 pkg.mSignatures, updateSignature)) {
2392 Log.e(TAG, "Package " + pkg.packageName
2393 + " has no signatures that match those in shared user "
2394 + pkgSetting.sharedUser.name + "; ignoring!");
2395 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2396 return false;
2397 }
2398 }
2399 } else {
2400 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2401 }
2402 return true;
2403 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002404
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002405 public boolean performDexOpt(String packageName) {
2406 if (!mNoDexOpt) {
2407 return false;
2408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002409
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002410 PackageParser.Package p;
2411 synchronized (mPackages) {
2412 p = mPackages.get(packageName);
2413 if (p == null || p.mDidDexOpt) {
2414 return false;
2415 }
2416 }
2417 synchronized (mInstallLock) {
2418 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2419 }
2420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002421
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002422 static final int DEX_OPT_SKIPPED = 0;
2423 static final int DEX_OPT_PERFORMED = 1;
2424 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002425
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002426 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2427 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002428 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002429 String path = pkg.mScanPath;
2430 int ret = 0;
2431 try {
2432 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002433 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002434 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002435 pkg.mDidDexOpt = true;
2436 performed = true;
2437 }
2438 } catch (FileNotFoundException e) {
2439 Log.w(TAG, "Apk not found for dexopt: " + path);
2440 ret = -1;
2441 } catch (IOException e) {
2442 Log.w(TAG, "Exception reading apk: " + path, e);
2443 ret = -1;
2444 }
2445 if (ret < 0) {
2446 //error from installer
2447 return DEX_OPT_FAILED;
2448 }
2449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002450
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002451 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2452 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002453
2454 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2455 return Environment.isEncryptedFilesystemEnabled() &&
2456 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2457 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002458
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002459 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2460 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2461 Log.w(TAG, "Unable to update from " + oldPkg.name
2462 + " to " + newPkg.packageName
2463 + ": old package not in system partition");
2464 return false;
2465 } else if (mPackages.get(oldPkg.name) != null) {
2466 Log.w(TAG, "Unable to update from " + oldPkg.name
2467 + " to " + newPkg.packageName
2468 + ": old package still exists");
2469 return false;
2470 }
2471 return true;
2472 }
2473
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002474 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2475 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002476 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002477 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2478 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002479 // Bail out. The resource and code paths haven't been set.
2480 Log.w(TAG, " Code and resource paths haven't been set correctly");
2481 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2482 return null;
2483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 mScanningPath = scanFile;
2485 if (pkg == null) {
2486 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2487 return null;
2488 }
2489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2491 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2492 }
2493
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002494 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 synchronized (mPackages) {
2496 if (mAndroidApplication != null) {
2497 Log.w(TAG, "*************************************************");
2498 Log.w(TAG, "Core android package being redefined. Skipping.");
2499 Log.w(TAG, " file=" + mScanningPath);
2500 Log.w(TAG, "*************************************************");
2501 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2502 return null;
2503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 // Set up information for our fall-back user intent resolution
2506 // activity.
2507 mPlatformPackage = pkg;
2508 pkg.mVersionCode = mSdkVersion;
2509 mAndroidApplication = pkg.applicationInfo;
2510 mResolveActivity.applicationInfo = mAndroidApplication;
2511 mResolveActivity.name = ResolverActivity.class.getName();
2512 mResolveActivity.packageName = mAndroidApplication.packageName;
2513 mResolveActivity.processName = mAndroidApplication.processName;
2514 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2515 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2516 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2517 mResolveActivity.exported = true;
2518 mResolveActivity.enabled = true;
2519 mResolveInfo.activityInfo = mResolveActivity;
2520 mResolveInfo.priority = 0;
2521 mResolveInfo.preferredOrder = 0;
2522 mResolveInfo.match = 0;
2523 mResolveComponentName = new ComponentName(
2524 mAndroidApplication.packageName, mResolveActivity.name);
2525 }
2526 }
2527
2528 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002529 TAG, "Scanning package " + pkg.packageName);
2530 if (mPackages.containsKey(pkg.packageName)
2531 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002533 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 + " already installed. Skipping duplicate.");
2535 Log.w(TAG, "*************************************************");
2536 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2537 return null;
2538 }
2539
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002540 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002541 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2542 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 SharedUserSetting suid = null;
2545 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002548
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002549 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2550 // Only system apps can use these features.
2551 pkg.mOriginalPackage = null;
2552 pkg.mRealPackage = null;
2553 pkg.mAdoptPermissions = null;
2554 }
2555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 synchronized (mPackages) {
2557 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002558 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2559 if (mTmpSharedLibraries == null ||
2560 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2561 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2562 }
2563 int num = 0;
2564 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2565 for (int i=0; i<N; i++) {
2566 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 if (file == null) {
2568 Log.e(TAG, "Package " + pkg.packageName
2569 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002570 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2572 return null;
2573 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002574 mTmpSharedLibraries[num] = file;
2575 num++;
2576 }
2577 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2578 for (int i=0; i<N; i++) {
2579 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2580 if (file == null) {
2581 Log.w(TAG, "Package " + pkg.packageName
2582 + " desires unavailable shared library "
2583 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2584 } else {
2585 mTmpSharedLibraries[num] = file;
2586 num++;
2587 }
2588 }
2589 if (num > 0) {
2590 pkg.usesLibraryFiles = new String[num];
2591 System.arraycopy(mTmpSharedLibraries, 0,
2592 pkg.usesLibraryFiles, 0, num);
2593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002594
Dianne Hackborn49237342009-08-27 20:08:01 -07002595 if (pkg.reqFeatures != null) {
2596 N = pkg.reqFeatures.size();
2597 for (int i=0; i<N; i++) {
2598 FeatureInfo fi = pkg.reqFeatures.get(i);
2599 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2600 // Don't care.
2601 continue;
2602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002603
Dianne Hackborn49237342009-08-27 20:08:01 -07002604 if (fi.name != null) {
2605 if (mAvailableFeatures.get(fi.name) == null) {
2606 Log.e(TAG, "Package " + pkg.packageName
2607 + " requires unavailable feature "
2608 + fi.name + "; failing!");
2609 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2610 return null;
2611 }
2612 }
2613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 }
2615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 if (pkg.mSharedUserId != null) {
2618 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2619 pkg.applicationInfo.flags, true);
2620 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 + " for shared user failed");
2623 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2624 return null;
2625 }
2626 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2627 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2628 + suid.userId + "): packages=" + suid.packages);
2629 }
2630 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002631
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002632 if (false) {
2633 if (pkg.mOriginalPackage != null) {
2634 Log.w(TAG, "WAITING FOR DEBUGGER");
2635 Debug.waitForDebugger();
2636 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2637 + pkg.mOriginalPackage);
2638 }
2639 }
2640
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002641 // Check if we are renaming from an original package name.
2642 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002643 String realName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002644 if (pkg.mOriginalPackage != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002645 // This package may need to be renamed to a previously
2646 // installed name. Let's check on that...
2647 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
2648 if (pkg.mOriginalPackage.equals(renamed)) {
2649 // This package had originally been installed as the
2650 // original name, and we have already taken care of
2651 // transitioning to the new one. Just update the new
2652 // one to continue using the old name.
2653 realName = pkg.mRealPackage;
2654 if (!pkg.packageName.equals(renamed)) {
2655 // Callers into this function may have already taken
2656 // care of renaming the package; only do it here if
2657 // it is not already done.
2658 pkg.setPackageName(renamed);
2659 }
2660
2661 } else if ((origPackage
2662 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2663 // We do have the package already installed under its
2664 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002665 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002666 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002667 origPackage = null;
2668 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002669 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002670 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2671 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2672 + " to " + pkg.packageName + ": old uid "
2673 + origPackage.sharedUser.name
2674 + " differs from " + pkg.mSharedUserId);
2675 origPackage = null;
2676 }
2677 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002678 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2679 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002680 }
2681 }
2682 }
2683
2684 if (mTransferedPackages.contains(pkg.packageName)) {
2685 Log.w(TAG, "Package " + pkg.packageName
2686 + " was transferred to another, but its .apk remains");
2687 }
2688
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002689 // Just create the setting, don't add it yet. For already existing packages
2690 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002691 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 destResourceFile, pkg.applicationInfo.flags, true, false);
2693 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002694 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2696 return null;
2697 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002698
2699 if (pkgSetting.origPackage != null) {
2700 // If we are first transitioning from an original package,
2701 // fix up the new package's name now. We need to do this after
2702 // looking up the package under its new name, so getPackageLP
2703 // can take care of fiddling things correctly.
2704 pkg.setPackageName(origPackage.name);
2705
2706 // File a report about this.
2707 String msg = "New package " + pkgSetting.realName
2708 + " renamed to replace old package " + pkgSetting.name;
2709 reportSettingsProblem(Log.WARN, msg);
2710
2711 // Make a note of it.
2712 mTransferedPackages.add(origPackage.name);
2713
2714 // No longer need to retain this.
2715 pkgSetting.origPackage = null;
2716 }
2717
2718 if (realName != null) {
2719 // Make a note of it.
2720 mTransferedPackages.add(pkg.packageName);
2721 }
2722
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002723 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 pkg.applicationInfo.uid = pkgSetting.userId;
2728 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002729
2730 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2732 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2733 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2734 return null;
2735 }
2736 // The signature has changed, but this package is in the system
2737 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002738 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 // However... if this package is part of a shared user, but it
2740 // doesn't match the signature of the shared user, let's fail.
2741 // What this means is that you can't change the signatures
2742 // associated with an overall shared user, which doesn't seem all
2743 // that unreasonable.
2744 if (pkgSetting.sharedUser != null) {
2745 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2746 pkg.mSignatures, false)) {
2747 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2748 return null;
2749 }
2750 }
2751 removeExisting = true;
2752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002753
The Android Open Source Project10592532009-03-18 17:39:46 -07002754 // Verify that this new package doesn't have any content providers
2755 // that conflict with existing packages. Only do this if the
2756 // package isn't already installed, since we don't want to break
2757 // things that are installed.
2758 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2759 int N = pkg.providers.size();
2760 int i;
2761 for (i=0; i<N; i++) {
2762 PackageParser.Provider p = pkg.providers.get(i);
2763 String names[] = p.info.authority.split(";");
2764 for (int j = 0; j < names.length; j++) {
2765 if (mProviders.containsKey(names[j])) {
2766 PackageParser.Provider other = mProviders.get(names[j]);
2767 Log.w(TAG, "Can't install because provider name " + names[j] +
2768 " (in package " + pkg.applicationInfo.packageName +
2769 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002770 + ((other != null && other.getComponentName() != null)
2771 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002772 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2773 return null;
2774 }
2775 }
2776 }
2777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 }
2779
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002780 final String pkgName = pkg.packageName;
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002783 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002785 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 if (ret != 0) {
2787 String msg = "System package " + pkg.packageName
2788 + " could not have data directory erased after signature change.";
2789 reportSettingsProblem(Log.WARN, msg);
2790 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2791 return null;
2792 }
2793 }
2794 Log.w(TAG, "System package " + pkg.packageName
2795 + " signature changed: existing data removed.");
2796 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2797 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002798
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002799 if (pkg.mAdoptPermissions != null) {
2800 // This package wants to adopt ownership of permissions from
2801 // another package.
2802 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2803 String origName = pkg.mAdoptPermissions.get(i);
2804 PackageSetting orig = mSettings.peekPackageLP(origName);
2805 if (orig != null) {
2806 if (verifyPackageUpdate(orig, pkg)) {
2807 Log.i(TAG, "Adopting permissions from "
2808 + origName + " to " + pkg.packageName);
2809 mSettings.transferPermissions(origName, pkg.packageName);
2810 }
2811 }
2812 }
2813 }
2814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 long scanFileTime = scanFile.lastModified();
2816 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2817 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2818 pkg.applicationInfo.processName = fixProcessName(
2819 pkg.applicationInfo.packageName,
2820 pkg.applicationInfo.processName,
2821 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822
2823 File dataPath;
2824 if (mPlatformPackage == pkg) {
2825 // The system package is special.
2826 dataPath = new File (Environment.getDataDirectory(), "system");
2827 pkg.applicationInfo.dataDir = dataPath.getPath();
2828 } else {
2829 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002830 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2831 if (useEncryptedFSDir) {
2832 dataPath = new File(mSecureAppDataDir, pkgName);
2833 } else {
2834 dataPath = new File(mAppDataDir, pkgName);
2835 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002836
2837 boolean uidError = false;
2838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 if (dataPath.exists()) {
2840 mOutPermissions[1] = 0;
2841 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2842 if (mOutPermissions[1] == pkg.applicationInfo.uid
2843 || !Process.supportsProcesses()) {
2844 pkg.applicationInfo.dataDir = dataPath.getPath();
2845 } else {
2846 boolean recovered = false;
2847 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2848 // If this is a system app, we can at least delete its
2849 // current data so the application will still work.
2850 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002851 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002852 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // Old data gone!
2854 String msg = "System package " + pkg.packageName
2855 + " has changed from uid: "
2856 + mOutPermissions[1] + " to "
2857 + pkg.applicationInfo.uid + "; old data erased";
2858 reportSettingsProblem(Log.WARN, msg);
2859 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002862 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 pkg.applicationInfo.uid);
2864 if (ret == -1) {
2865 // Ack should not happen!
2866 msg = "System package " + pkg.packageName
2867 + " could not have data directory re-created after delete.";
2868 reportSettingsProblem(Log.WARN, msg);
2869 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2870 return null;
2871 }
2872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 if (!recovered) {
2875 mHasSystemUidErrors = true;
2876 }
2877 }
2878 if (!recovered) {
2879 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2880 + pkg.applicationInfo.uid + "/fs_"
2881 + mOutPermissions[1];
2882 String msg = "Package " + pkg.packageName
2883 + " has mismatched uid: "
2884 + mOutPermissions[1] + " on disk, "
2885 + pkg.applicationInfo.uid + " in settings";
2886 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002887 mSettings.mReadMessages.append(msg);
2888 mSettings.mReadMessages.append('\n');
2889 uidError = true;
2890 if (!pkgSetting.uidError) {
2891 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
2894 }
2895 }
2896 pkg.applicationInfo.dataDir = dataPath.getPath();
2897 } else {
2898 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2899 Log.v(TAG, "Want this data dir: " + dataPath);
2900 //invoke installer to do the actual installation
2901 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002902 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 pkg.applicationInfo.uid);
2904 if(ret < 0) {
2905 // Error from installer
2906 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2907 return null;
2908 }
2909 } else {
2910 dataPath.mkdirs();
2911 if (dataPath.exists()) {
2912 FileUtils.setPermissions(
2913 dataPath.toString(),
2914 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2915 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2916 }
2917 }
2918 if (dataPath.exists()) {
2919 pkg.applicationInfo.dataDir = dataPath.getPath();
2920 } else {
2921 Log.w(TAG, "Unable to create data directory: " + dataPath);
2922 pkg.applicationInfo.dataDir = null;
2923 }
2924 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002925
2926 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 }
2928
2929 // Perform shared library installation and dex validation and
2930 // optimization, if this is not a system app.
2931 if (mInstaller != null) {
2932 String path = scanFile.getPath();
2933 if (scanFileNewer) {
2934 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002935 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2936 if (err != PackageManager.INSTALL_SUCCEEDED) {
2937 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 return null;
2939 }
2940 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002941 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002942
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002943 if ((scanMode&SCAN_NO_DEX) == 0) {
2944 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2946 return null;
2947 }
2948 }
2949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 if (mFactoryTest && pkg.requestedPermissions.contains(
2952 android.Manifest.permission.FACTORY_TEST)) {
2953 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2954 }
2955
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002956 // Request the ActivityManager to kill the process(only for existing packages)
2957 // so that we do not end up in a confused state while the user is still using the older
2958 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002959 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002960 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002961 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002962 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002965 // We don't expect installation to fail beyond this point,
2966 if ((scanMode&SCAN_MONITOR) != 0) {
2967 mAppDirs.put(pkg.mPath, pkg);
2968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002970 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002972 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002973 // Make sure we don't accidentally delete its data.
2974 mSettings.mPackagesToBeCleaned.remove(pkgName);
2975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 int N = pkg.providers.size();
2977 StringBuilder r = null;
2978 int i;
2979 for (i=0; i<N; i++) {
2980 PackageParser.Provider p = pkg.providers.get(i);
2981 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2982 p.info.processName, pkg.applicationInfo.uid);
2983 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2984 p.info.name), p);
2985 p.syncable = p.info.isSyncable;
2986 String names[] = p.info.authority.split(";");
2987 p.info.authority = null;
2988 for (int j = 0; j < names.length; j++) {
2989 if (j == 1 && p.syncable) {
2990 // We only want the first authority for a provider to possibly be
2991 // syncable, so if we already added this provider using a different
2992 // authority clear the syncable flag. We copy the provider before
2993 // changing it because the mProviders object contains a reference
2994 // to a provider that we don't want to change.
2995 // Only do this for the second authority since the resulting provider
2996 // object can be the same for all future authorities for this provider.
2997 p = new PackageParser.Provider(p);
2998 p.syncable = false;
2999 }
3000 if (!mProviders.containsKey(names[j])) {
3001 mProviders.put(names[j], p);
3002 if (p.info.authority == null) {
3003 p.info.authority = names[j];
3004 } else {
3005 p.info.authority = p.info.authority + ";" + names[j];
3006 }
3007 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3008 Log.d(TAG, "Registered content provider: " + names[j] +
3009 ", className = " + p.info.name +
3010 ", isSyncable = " + p.info.isSyncable);
3011 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07003012 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 Log.w(TAG, "Skipping provider name " + names[j] +
3014 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07003015 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003016 + ((other != null && other.getComponentName() != null)
3017 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 }
3019 }
3020 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3021 if (r == null) {
3022 r = new StringBuilder(256);
3023 } else {
3024 r.append(' ');
3025 }
3026 r.append(p.info.name);
3027 }
3028 }
3029 if (r != null) {
3030 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 N = pkg.services.size();
3034 r = null;
3035 for (i=0; i<N; i++) {
3036 PackageParser.Service s = pkg.services.get(i);
3037 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3038 s.info.processName, pkg.applicationInfo.uid);
3039 mServices.addService(s);
3040 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3041 if (r == null) {
3042 r = new StringBuilder(256);
3043 } else {
3044 r.append(' ');
3045 }
3046 r.append(s.info.name);
3047 }
3048 }
3049 if (r != null) {
3050 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 N = pkg.receivers.size();
3054 r = null;
3055 for (i=0; i<N; i++) {
3056 PackageParser.Activity a = pkg.receivers.get(i);
3057 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3058 a.info.processName, pkg.applicationInfo.uid);
3059 mReceivers.addActivity(a, "receiver");
3060 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3061 if (r == null) {
3062 r = new StringBuilder(256);
3063 } else {
3064 r.append(' ');
3065 }
3066 r.append(a.info.name);
3067 }
3068 }
3069 if (r != null) {
3070 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 N = pkg.activities.size();
3074 r = null;
3075 for (i=0; i<N; i++) {
3076 PackageParser.Activity a = pkg.activities.get(i);
3077 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3078 a.info.processName, pkg.applicationInfo.uid);
3079 mActivities.addActivity(a, "activity");
3080 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3081 if (r == null) {
3082 r = new StringBuilder(256);
3083 } else {
3084 r.append(' ');
3085 }
3086 r.append(a.info.name);
3087 }
3088 }
3089 if (r != null) {
3090 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 N = pkg.permissionGroups.size();
3094 r = null;
3095 for (i=0; i<N; i++) {
3096 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3097 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3098 if (cur == null) {
3099 mPermissionGroups.put(pg.info.name, pg);
3100 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3101 if (r == null) {
3102 r = new StringBuilder(256);
3103 } else {
3104 r.append(' ');
3105 }
3106 r.append(pg.info.name);
3107 }
3108 } else {
3109 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3110 + pg.info.packageName + " ignored: original from "
3111 + cur.info.packageName);
3112 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3113 if (r == null) {
3114 r = new StringBuilder(256);
3115 } else {
3116 r.append(' ');
3117 }
3118 r.append("DUP:");
3119 r.append(pg.info.name);
3120 }
3121 }
3122 }
3123 if (r != null) {
3124 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 N = pkg.permissions.size();
3128 r = null;
3129 for (i=0; i<N; i++) {
3130 PackageParser.Permission p = pkg.permissions.get(i);
3131 HashMap<String, BasePermission> permissionMap =
3132 p.tree ? mSettings.mPermissionTrees
3133 : mSettings.mPermissions;
3134 p.group = mPermissionGroups.get(p.info.group);
3135 if (p.info.group == null || p.group != null) {
3136 BasePermission bp = permissionMap.get(p.info.name);
3137 if (bp == null) {
3138 bp = new BasePermission(p.info.name, p.info.packageName,
3139 BasePermission.TYPE_NORMAL);
3140 permissionMap.put(p.info.name, bp);
3141 }
3142 if (bp.perm == null) {
3143 if (bp.sourcePackage == null
3144 || bp.sourcePackage.equals(p.info.packageName)) {
3145 BasePermission tree = findPermissionTreeLP(p.info.name);
3146 if (tree == null
3147 || tree.sourcePackage.equals(p.info.packageName)) {
3148 bp.perm = p;
3149 bp.uid = pkg.applicationInfo.uid;
3150 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3151 if (r == null) {
3152 r = new StringBuilder(256);
3153 } else {
3154 r.append(' ');
3155 }
3156 r.append(p.info.name);
3157 }
3158 } else {
3159 Log.w(TAG, "Permission " + p.info.name + " from package "
3160 + p.info.packageName + " ignored: base tree "
3161 + tree.name + " is from package "
3162 + tree.sourcePackage);
3163 }
3164 } else {
3165 Log.w(TAG, "Permission " + p.info.name + " from package "
3166 + p.info.packageName + " ignored: original from "
3167 + bp.sourcePackage);
3168 }
3169 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3170 if (r == null) {
3171 r = new StringBuilder(256);
3172 } else {
3173 r.append(' ');
3174 }
3175 r.append("DUP:");
3176 r.append(p.info.name);
3177 }
3178 } else {
3179 Log.w(TAG, "Permission " + p.info.name + " from package "
3180 + p.info.packageName + " ignored: no group "
3181 + p.group);
3182 }
3183 }
3184 if (r != null) {
3185 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 N = pkg.instrumentation.size();
3189 r = null;
3190 for (i=0; i<N; i++) {
3191 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3192 a.info.packageName = pkg.applicationInfo.packageName;
3193 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3194 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3195 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003196 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3198 if (r == null) {
3199 r = new StringBuilder(256);
3200 } else {
3201 r.append(' ');
3202 }
3203 r.append(a.info.name);
3204 }
3205 }
3206 if (r != null) {
3207 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003209
Dianne Hackborn854060af2009-07-09 18:14:31 -07003210 if (pkg.protectedBroadcasts != null) {
3211 N = pkg.protectedBroadcasts.size();
3212 for (i=0; i<N; i++) {
3213 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3214 }
3215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 pkgSetting.setTimeStamp(scanFileTime);
3218 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 return pkg;
3221 }
3222
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003223 private void killApplication(String pkgName, int uid) {
3224 // Request the ActivityManager to kill the process(only for existing packages)
3225 // so that we do not end up in a confused state while the user is still using the older
3226 // version of the application while the new one gets installed.
3227 IActivityManager am = ActivityManagerNative.getDefault();
3228 if (am != null) {
3229 try {
3230 am.killApplicationWithUid(pkgName, uid);
3231 } catch (RemoteException e) {
3232 }
3233 }
3234 }
3235
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003236 // The following constants are returned by cachePackageSharedLibsForAbiLI
3237 // to indicate if native shared libraries were found in the package.
3238 // Values are:
3239 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3240 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3241 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3242 // in package (and not installed)
3243 //
3244 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3245 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3246 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003248 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3249 // and automatically copy them to /data/data/<appname>/lib if present.
3250 //
3251 // NOTE: this method may throw an IOException if the library cannot
3252 // be copied to its final destination, e.g. if there isn't enough
3253 // room left on the data partition, or a ZipException if the package
3254 // file is malformed.
3255 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003256 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3257 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003258 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3259 final String apkLib = "lib/";
3260 final int apkLibLen = apkLib.length();
3261 final int cpuAbiLen = cpuAbi.length();
3262 final String libPrefix = "lib";
3263 final int libPrefixLen = libPrefix.length();
3264 final String libSuffix = ".so";
3265 final int libSuffixLen = libSuffix.length();
3266 boolean hasNativeLibraries = false;
3267 boolean installedNativeLibraries = false;
3268
3269 // the minimum length of a valid native shared library of the form
3270 // lib/<something>/lib<name>.so.
3271 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3272
3273 ZipFile zipFile = new ZipFile(scanFile);
3274 Enumeration<ZipEntry> entries =
3275 (Enumeration<ZipEntry>) zipFile.entries();
3276
3277 while (entries.hasMoreElements()) {
3278 ZipEntry entry = entries.nextElement();
3279 // skip directories
3280 if (entry.isDirectory()) {
3281 continue;
3282 }
3283 String entryName = entry.getName();
3284
3285 // check that the entry looks like lib/<something>/lib<name>.so
3286 // here, but don't check the ABI just yet.
3287 //
3288 // - must be sufficiently long
3289 // - must end with libSuffix, i.e. ".so"
3290 // - must start with apkLib, i.e. "lib/"
3291 if (entryName.length() < minEntryLen ||
3292 !entryName.endsWith(libSuffix) ||
3293 !entryName.startsWith(apkLib) ) {
3294 continue;
3295 }
3296
3297 // file name must start with libPrefix, i.e. "lib"
3298 int lastSlash = entryName.lastIndexOf('/');
3299
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003300 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003301 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3302 continue;
3303 }
3304
3305 hasNativeLibraries = true;
3306
3307 // check the cpuAbi now, between lib/ and /lib<name>.so
3308 //
3309 if (lastSlash != apkLibLen + cpuAbiLen ||
3310 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3311 continue;
3312
3313 // extract the library file name, ensure it doesn't contain
3314 // weird characters. we're guaranteed here that it doesn't contain
3315 // a directory separator though.
3316 String libFileName = entryName.substring(lastSlash+1);
3317 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3318 continue;
3319 }
3320
3321 installedNativeLibraries = true;
3322
3323 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3324 File.separator + libFileName;
3325 File sharedLibraryFile = new File(sharedLibraryFilePath);
3326 if (! sharedLibraryFile.exists() ||
3327 sharedLibraryFile.length() != entry.getSize() ||
3328 sharedLibraryFile.lastModified() != entry.getTime()) {
3329 if (Config.LOGD) {
3330 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003332 if (mInstaller == null) {
3333 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003334 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003335 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003336 sharedLibraryFile);
3337 }
3338 }
3339 if (!hasNativeLibraries)
3340 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3341
3342 if (!installedNativeLibraries)
3343 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3344
3345 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3346 }
3347
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003348 // Find the gdbserver executable program in a package at
3349 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3350 //
3351 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3352 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3353 //
3354 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3355 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3356 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3357 final String GDBSERVER = "gdbserver";
3358 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3359
3360 ZipFile zipFile = new ZipFile(scanFile);
3361 Enumeration<ZipEntry> entries =
3362 (Enumeration<ZipEntry>) zipFile.entries();
3363
3364 while (entries.hasMoreElements()) {
3365 ZipEntry entry = entries.nextElement();
3366 // skip directories
3367 if (entry.isDirectory()) {
3368 continue;
3369 }
3370 String entryName = entry.getName();
3371
3372 if (!entryName.equals(apkGdbServerPath)) {
3373 continue;
3374 }
3375
3376 String installGdbServerPath = installGdbServerDir.getPath() +
3377 "/" + GDBSERVER;
3378 File installGdbServerFile = new File(installGdbServerPath);
3379 if (! installGdbServerFile.exists() ||
3380 installGdbServerFile.length() != entry.getSize() ||
3381 installGdbServerFile.lastModified() != entry.getTime()) {
3382 if (Config.LOGD) {
3383 Log.d(TAG, "Caching gdbserver " + entry.getName());
3384 }
3385 if (mInstaller == null) {
3386 installGdbServerDir.mkdir();
3387 }
3388 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3389 installGdbServerFile);
3390 }
3391 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3392 }
3393 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3394 }
3395
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003396 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3397 // and copy them to /data/data/<appname>/lib.
3398 //
3399 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3400 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3401 // one if ro.product.cpu.abi2 is defined.
3402 //
3403 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3404 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003405 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003406 try {
3407 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3408
3409 // some architectures are capable of supporting several CPU ABIs
3410 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3411 // this is indicated by the definition of the ro.product.cpu.abi2
3412 // system property.
3413 //
3414 // only scan the package twice in case of ABI mismatch
3415 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003416 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003417 if (cpuAbi2 != null) {
3418 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003420
3421 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3422 Log.w(TAG,"Native ABI mismatch from package file");
3423 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003425
3426 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3427 cpuAbi = cpuAbi2;
3428 }
3429 }
3430
3431 // for debuggable packages, also extract gdbserver from lib/<abi>
3432 // into /data/data/<appname>/lib too.
3433 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3434 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3435 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3436 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3437 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003440 } catch (ZipException e) {
3441 Log.w(TAG, "Failed to extract data from package file", e);
3442 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003444 Log.w(TAG, "Failed to cache package shared libs", e);
3445 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003447 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003450 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003452 File binaryDir,
3453 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 InputStream inputStream = zipFile.getInputStream(entry);
3455 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003456 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003458 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 // now need to be left as world readable and owned by the system.
3460 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3461 ! tempFile.setLastModified(entry.getTime()) ||
3462 FileUtils.setPermissions(tempFilePath,
3463 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003464 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003466 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 // Failed to properly write file.
3468 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003469 throw new IOException("Couldn't create cached binary "
3470 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 }
3472 } finally {
3473 inputStream.close();
3474 }
3475 }
3476
3477 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3478 if (chatty && Config.LOGD) Log.d(
3479 TAG, "Removing package " + pkg.applicationInfo.packageName );
3480
3481 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 mPackages.remove(pkg.applicationInfo.packageName);
3485 if (pkg.mPath != null) {
3486 mAppDirs.remove(pkg.mPath);
3487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 PackageSetting ps = (PackageSetting)pkg.mExtras;
3490 if (ps != null && ps.sharedUser != null) {
3491 // XXX don't do this until the data is removed.
3492 if (false) {
3493 ps.sharedUser.packages.remove(ps);
3494 if (ps.sharedUser.packages.size() == 0) {
3495 // Remove.
3496 }
3497 }
3498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 int N = pkg.providers.size();
3501 StringBuilder r = null;
3502 int i;
3503 for (i=0; i<N; i++) {
3504 PackageParser.Provider p = pkg.providers.get(i);
3505 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3506 p.info.name));
3507 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 /* The is another ContentProvider with this authority when
3510 * this app was installed so this authority is null,
3511 * Ignore it as we don't have to unregister the provider.
3512 */
3513 continue;
3514 }
3515 String names[] = p.info.authority.split(";");
3516 for (int j = 0; j < names.length; j++) {
3517 if (mProviders.get(names[j]) == p) {
3518 mProviders.remove(names[j]);
3519 if (chatty && Config.LOGD) Log.d(
3520 TAG, "Unregistered content provider: " + names[j] +
3521 ", className = " + p.info.name +
3522 ", isSyncable = " + p.info.isSyncable);
3523 }
3524 }
3525 if (chatty) {
3526 if (r == null) {
3527 r = new StringBuilder(256);
3528 } else {
3529 r.append(' ');
3530 }
3531 r.append(p.info.name);
3532 }
3533 }
3534 if (r != null) {
3535 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 N = pkg.services.size();
3539 r = null;
3540 for (i=0; i<N; i++) {
3541 PackageParser.Service s = pkg.services.get(i);
3542 mServices.removeService(s);
3543 if (chatty) {
3544 if (r == null) {
3545 r = new StringBuilder(256);
3546 } else {
3547 r.append(' ');
3548 }
3549 r.append(s.info.name);
3550 }
3551 }
3552 if (r != null) {
3553 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 N = pkg.receivers.size();
3557 r = null;
3558 for (i=0; i<N; i++) {
3559 PackageParser.Activity a = pkg.receivers.get(i);
3560 mReceivers.removeActivity(a, "receiver");
3561 if (chatty) {
3562 if (r == null) {
3563 r = new StringBuilder(256);
3564 } else {
3565 r.append(' ');
3566 }
3567 r.append(a.info.name);
3568 }
3569 }
3570 if (r != null) {
3571 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 N = pkg.activities.size();
3575 r = null;
3576 for (i=0; i<N; i++) {
3577 PackageParser.Activity a = pkg.activities.get(i);
3578 mActivities.removeActivity(a, "activity");
3579 if (chatty) {
3580 if (r == null) {
3581 r = new StringBuilder(256);
3582 } else {
3583 r.append(' ');
3584 }
3585 r.append(a.info.name);
3586 }
3587 }
3588 if (r != null) {
3589 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 N = pkg.permissions.size();
3593 r = null;
3594 for (i=0; i<N; i++) {
3595 PackageParser.Permission p = pkg.permissions.get(i);
3596 boolean tree = false;
3597 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3598 if (bp == null) {
3599 tree = true;
3600 bp = mSettings.mPermissionTrees.get(p.info.name);
3601 }
3602 if (bp != null && bp.perm == p) {
3603 if (bp.type != BasePermission.TYPE_BUILTIN) {
3604 if (tree) {
3605 mSettings.mPermissionTrees.remove(p.info.name);
3606 } else {
3607 mSettings.mPermissions.remove(p.info.name);
3608 }
3609 } else {
3610 bp.perm = null;
3611 }
3612 if (chatty) {
3613 if (r == null) {
3614 r = new StringBuilder(256);
3615 } else {
3616 r.append(' ');
3617 }
3618 r.append(p.info.name);
3619 }
3620 }
3621 }
3622 if (r != null) {
3623 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 N = pkg.instrumentation.size();
3627 r = null;
3628 for (i=0; i<N; i++) {
3629 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003630 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 if (chatty) {
3632 if (r == null) {
3633 r = new StringBuilder(256);
3634 } else {
3635 r.append(' ');
3636 }
3637 r.append(a.info.name);
3638 }
3639 }
3640 if (r != null) {
3641 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3642 }
3643 }
3644 }
3645
3646 private static final boolean isPackageFilename(String name) {
3647 return name != null && name.endsWith(".apk");
3648 }
3649
3650 private void updatePermissionsLP() {
3651 // Make sure there are no dangling permission trees.
3652 Iterator<BasePermission> it = mSettings.mPermissionTrees
3653 .values().iterator();
3654 while (it.hasNext()) {
3655 BasePermission bp = it.next();
3656 if (bp.perm == null) {
3657 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3658 + " from package " + bp.sourcePackage);
3659 it.remove();
3660 }
3661 }
3662
3663 // Make sure all dynamic permissions have been assigned to a package,
3664 // and make sure there are no dangling permissions.
3665 it = mSettings.mPermissions.values().iterator();
3666 while (it.hasNext()) {
3667 BasePermission bp = it.next();
3668 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3669 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3670 + bp.name + " pkg=" + bp.sourcePackage
3671 + " info=" + bp.pendingInfo);
3672 if (bp.perm == null && bp.pendingInfo != null) {
3673 BasePermission tree = findPermissionTreeLP(bp.name);
3674 if (tree != null) {
3675 bp.perm = new PackageParser.Permission(tree.perm.owner,
3676 new PermissionInfo(bp.pendingInfo));
3677 bp.perm.info.packageName = tree.perm.info.packageName;
3678 bp.perm.info.name = bp.name;
3679 bp.uid = tree.uid;
3680 }
3681 }
3682 }
3683 if (bp.perm == null) {
3684 Log.w(TAG, "Removing dangling permission: " + bp.name
3685 + " from package " + bp.sourcePackage);
3686 it.remove();
3687 }
3688 }
3689
3690 // Now update the permissions for all packages, in particular
3691 // replace the granted permissions of the system packages.
3692 for (PackageParser.Package pkg : mPackages.values()) {
3693 grantPermissionsLP(pkg, false);
3694 }
3695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3698 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3699 if (ps == null) {
3700 return;
3701 }
3702 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3703 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 if (replace) {
3706 ps.permissionsFixed = false;
3707 if (gp == ps) {
3708 gp.grantedPermissions.clear();
3709 gp.gids = mGlobalGids;
3710 }
3711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 if (gp.gids == null) {
3714 gp.gids = mGlobalGids;
3715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 final int N = pkg.requestedPermissions.size();
3718 for (int i=0; i<N; i++) {
3719 String name = pkg.requestedPermissions.get(i);
3720 BasePermission bp = mSettings.mPermissions.get(name);
3721 PackageParser.Permission p = bp != null ? bp.perm : null;
3722 if (false) {
3723 if (gp != ps) {
3724 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3725 + ": " + p);
3726 }
3727 }
3728 if (p != null) {
3729 final String perm = p.info.name;
3730 boolean allowed;
3731 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3732 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3733 allowed = true;
3734 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3735 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003736 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003738 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 == PackageManager.SIGNATURE_MATCH);
3740 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3741 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3742 // For updated system applications, the signatureOrSystem permission
3743 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003744 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3746 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3747 if(sysPs.grantedPermissions.contains(perm)) {
3748 allowed = true;
3749 } else {
3750 allowed = false;
3751 }
3752 } else {
3753 allowed = true;
3754 }
3755 }
3756 }
3757 } else {
3758 allowed = false;
3759 }
3760 if (false) {
3761 if (gp != ps) {
3762 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3763 }
3764 }
3765 if (allowed) {
3766 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3767 && ps.permissionsFixed) {
3768 // If this is an existing, non-system package, then
3769 // we can't add any new permissions to it.
3770 if (!gp.loadedPermissions.contains(perm)) {
3771 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003772 // Except... if this is a permission that was added
3773 // to the platform (note: need to only do this when
3774 // updating the platform).
3775 final int NP = PackageParser.NEW_PERMISSIONS.length;
3776 for (int ip=0; ip<NP; ip++) {
3777 final PackageParser.NewPermissionInfo npi
3778 = PackageParser.NEW_PERMISSIONS[ip];
3779 if (npi.name.equals(perm)
3780 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3781 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003782 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003783 + pkg.packageName);
3784 break;
3785 }
3786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 }
3788 }
3789 if (allowed) {
3790 if (!gp.grantedPermissions.contains(perm)) {
3791 addedPermission = true;
3792 gp.grantedPermissions.add(perm);
3793 gp.gids = appendInts(gp.gids, bp.gids);
3794 }
3795 } else {
3796 Log.w(TAG, "Not granting permission " + perm
3797 + " to package " + pkg.packageName
3798 + " because it was previously installed without");
3799 }
3800 } else {
3801 Log.w(TAG, "Not granting permission " + perm
3802 + " to package " + pkg.packageName
3803 + " (protectionLevel=" + p.info.protectionLevel
3804 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3805 + ")");
3806 }
3807 } else {
3808 Log.w(TAG, "Unknown permission " + name
3809 + " in package " + pkg.packageName);
3810 }
3811 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003814 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3815 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 // This is the first that we have heard about this package, so the
3817 // permissions we have now selected are fixed until explicitly
3818 // changed.
3819 ps.permissionsFixed = true;
3820 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3821 }
3822 }
3823
3824 private final class ActivityIntentResolver
3825 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003826 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003828 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 }
3830
Mihai Preda074edef2009-05-18 17:13:31 +02003831 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003833 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3835 }
3836
Mihai Predaeae850c2009-05-13 10:13:48 +02003837 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3838 ArrayList<PackageParser.Activity> packageActivities) {
3839 if (packageActivities == null) {
3840 return null;
3841 }
3842 mFlags = flags;
3843 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3844 int N = packageActivities.size();
3845 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3846 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003847
3848 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003849 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003850 intentFilters = packageActivities.get(i).intents;
3851 if (intentFilters != null && intentFilters.size() > 0) {
3852 listCut.add(intentFilters);
3853 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003854 }
3855 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3856 }
3857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003859 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 if (SHOW_INFO || Config.LOGV) Log.v(
3861 TAG, " " + type + " " +
3862 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3863 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3864 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003865 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3867 if (SHOW_INFO || Config.LOGV) {
3868 Log.v(TAG, " IntentFilter:");
3869 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3870 }
3871 if (!intent.debugCheck()) {
3872 Log.w(TAG, "==> For Activity " + a.info.name);
3873 }
3874 addFilter(intent);
3875 }
3876 }
3877
3878 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003879 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 if (SHOW_INFO || Config.LOGV) Log.v(
3881 TAG, " " + type + " " +
3882 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3883 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3884 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003885 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3887 if (SHOW_INFO || Config.LOGV) {
3888 Log.v(TAG, " IntentFilter:");
3889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3890 }
3891 removeFilter(intent);
3892 }
3893 }
3894
3895 @Override
3896 protected boolean allowFilterResult(
3897 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3898 ActivityInfo filterAi = filter.activity.info;
3899 for (int i=dest.size()-1; i>=0; i--) {
3900 ActivityInfo destAi = dest.get(i).activityInfo;
3901 if (destAi.name == filterAi.name
3902 && destAi.packageName == filterAi.packageName) {
3903 return false;
3904 }
3905 }
3906 return true;
3907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 @Override
3910 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3911 int match) {
3912 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3913 return null;
3914 }
3915 final PackageParser.Activity activity = info.activity;
3916 if (mSafeMode && (activity.info.applicationInfo.flags
3917 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3918 return null;
3919 }
3920 final ResolveInfo res = new ResolveInfo();
3921 res.activityInfo = PackageParser.generateActivityInfo(activity,
3922 mFlags);
3923 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3924 res.filter = info;
3925 }
3926 res.priority = info.getPriority();
3927 res.preferredOrder = activity.owner.mPreferredOrder;
3928 //System.out.println("Result: " + res.activityInfo.className +
3929 // " = " + res.priority);
3930 res.match = match;
3931 res.isDefault = info.hasDefault;
3932 res.labelRes = info.labelRes;
3933 res.nonLocalizedLabel = info.nonLocalizedLabel;
3934 res.icon = info.icon;
3935 return res;
3936 }
3937
3938 @Override
3939 protected void sortResults(List<ResolveInfo> results) {
3940 Collections.sort(results, mResolvePrioritySorter);
3941 }
3942
3943 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003944 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003946 out.print(prefix); out.print(
3947 Integer.toHexString(System.identityHashCode(filter.activity)));
3948 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003949 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 }
3951
3952// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3953// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3954// final List<ResolveInfo> retList = Lists.newArrayList();
3955// while (i.hasNext()) {
3956// final ResolveInfo resolveInfo = i.next();
3957// if (isEnabledLP(resolveInfo.activityInfo)) {
3958// retList.add(resolveInfo);
3959// }
3960// }
3961// return retList;
3962// }
3963
3964 // Keys are String (activity class name), values are Activity.
3965 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3966 = new HashMap<ComponentName, PackageParser.Activity>();
3967 private int mFlags;
3968 }
3969
3970 private final class ServiceIntentResolver
3971 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003972 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003974 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 }
3976
Mihai Preda074edef2009-05-18 17:13:31 +02003977 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003979 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3981 }
3982
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003983 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3984 ArrayList<PackageParser.Service> packageServices) {
3985 if (packageServices == null) {
3986 return null;
3987 }
3988 mFlags = flags;
3989 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3990 int N = packageServices.size();
3991 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3992 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3993
3994 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3995 for (int i = 0; i < N; ++i) {
3996 intentFilters = packageServices.get(i).intents;
3997 if (intentFilters != null && intentFilters.size() > 0) {
3998 listCut.add(intentFilters);
3999 }
4000 }
4001 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4002 }
4003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004005 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 if (SHOW_INFO || Config.LOGV) Log.v(
4007 TAG, " " + (s.info.nonLocalizedLabel != null
4008 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4009 if (SHOW_INFO || Config.LOGV) Log.v(
4010 TAG, " Class=" + s.info.name);
4011 int NI = s.intents.size();
4012 int j;
4013 for (j=0; j<NI; j++) {
4014 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4015 if (SHOW_INFO || Config.LOGV) {
4016 Log.v(TAG, " IntentFilter:");
4017 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4018 }
4019 if (!intent.debugCheck()) {
4020 Log.w(TAG, "==> For Service " + s.info.name);
4021 }
4022 addFilter(intent);
4023 }
4024 }
4025
4026 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004027 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 if (SHOW_INFO || Config.LOGV) Log.v(
4029 TAG, " " + (s.info.nonLocalizedLabel != null
4030 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4031 if (SHOW_INFO || Config.LOGV) Log.v(
4032 TAG, " Class=" + s.info.name);
4033 int NI = s.intents.size();
4034 int j;
4035 for (j=0; j<NI; j++) {
4036 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4037 if (SHOW_INFO || Config.LOGV) {
4038 Log.v(TAG, " IntentFilter:");
4039 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4040 }
4041 removeFilter(intent);
4042 }
4043 }
4044
4045 @Override
4046 protected boolean allowFilterResult(
4047 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4048 ServiceInfo filterSi = filter.service.info;
4049 for (int i=dest.size()-1; i>=0; i--) {
4050 ServiceInfo destAi = dest.get(i).serviceInfo;
4051 if (destAi.name == filterSi.name
4052 && destAi.packageName == filterSi.packageName) {
4053 return false;
4054 }
4055 }
4056 return true;
4057 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 @Override
4060 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4061 int match) {
4062 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4063 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4064 return null;
4065 }
4066 final PackageParser.Service service = info.service;
4067 if (mSafeMode && (service.info.applicationInfo.flags
4068 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4069 return null;
4070 }
4071 final ResolveInfo res = new ResolveInfo();
4072 res.serviceInfo = PackageParser.generateServiceInfo(service,
4073 mFlags);
4074 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4075 res.filter = filter;
4076 }
4077 res.priority = info.getPriority();
4078 res.preferredOrder = service.owner.mPreferredOrder;
4079 //System.out.println("Result: " + res.activityInfo.className +
4080 // " = " + res.priority);
4081 res.match = match;
4082 res.isDefault = info.hasDefault;
4083 res.labelRes = info.labelRes;
4084 res.nonLocalizedLabel = info.nonLocalizedLabel;
4085 res.icon = info.icon;
4086 return res;
4087 }
4088
4089 @Override
4090 protected void sortResults(List<ResolveInfo> results) {
4091 Collections.sort(results, mResolvePrioritySorter);
4092 }
4093
4094 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004095 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004097 out.print(prefix); out.print(
4098 Integer.toHexString(System.identityHashCode(filter.service)));
4099 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004100 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
4102
4103// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4104// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4105// final List<ResolveInfo> retList = Lists.newArrayList();
4106// while (i.hasNext()) {
4107// final ResolveInfo resolveInfo = (ResolveInfo) i;
4108// if (isEnabledLP(resolveInfo.serviceInfo)) {
4109// retList.add(resolveInfo);
4110// }
4111// }
4112// return retList;
4113// }
4114
4115 // Keys are String (activity class name), values are Activity.
4116 private final HashMap<ComponentName, PackageParser.Service> mServices
4117 = new HashMap<ComponentName, PackageParser.Service>();
4118 private int mFlags;
4119 };
4120
4121 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4122 new Comparator<ResolveInfo>() {
4123 public int compare(ResolveInfo r1, ResolveInfo r2) {
4124 int v1 = r1.priority;
4125 int v2 = r2.priority;
4126 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4127 if (v1 != v2) {
4128 return (v1 > v2) ? -1 : 1;
4129 }
4130 v1 = r1.preferredOrder;
4131 v2 = r2.preferredOrder;
4132 if (v1 != v2) {
4133 return (v1 > v2) ? -1 : 1;
4134 }
4135 if (r1.isDefault != r2.isDefault) {
4136 return r1.isDefault ? -1 : 1;
4137 }
4138 v1 = r1.match;
4139 v2 = r2.match;
4140 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4141 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4142 }
4143 };
4144
4145 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4146 new Comparator<ProviderInfo>() {
4147 public int compare(ProviderInfo p1, ProviderInfo p2) {
4148 final int v1 = p1.initOrder;
4149 final int v2 = p2.initOrder;
4150 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4151 }
4152 };
4153
4154 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4155 IActivityManager am = ActivityManagerNative.getDefault();
4156 if (am != null) {
4157 try {
4158 final Intent intent = new Intent(action,
4159 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4160 if (extras != null) {
4161 intent.putExtras(extras);
4162 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004163 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 am.broadcastIntent(
4165 null, intent,
4166 null, null, 0, null, null, null, false, false);
4167 } catch (RemoteException ex) {
4168 }
4169 }
4170 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004171
4172 public String nextPackageToClean(String lastPackage) {
4173 synchronized (mPackages) {
4174 if (!mMediaMounted) {
4175 // If the external storage is no longer mounted at this point,
4176 // the caller may not have been able to delete all of this
4177 // packages files and can not delete any more. Bail.
4178 return null;
4179 }
4180 if (lastPackage != null) {
4181 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4182 }
4183 return mSettings.mPackagesToBeCleaned.size() > 0
4184 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4185 }
4186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004188 void schedulePackageCleaning(String packageName) {
4189 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4190 }
4191
4192 void startCleaningPackages() {
4193 synchronized (mPackages) {
4194 if (!mMediaMounted) {
4195 return;
4196 }
4197 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4198 return;
4199 }
4200 }
4201 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4202 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4203 IActivityManager am = ActivityManagerNative.getDefault();
4204 if (am != null) {
4205 try {
4206 am.startService(null, intent, null);
4207 } catch (RemoteException e) {
4208 }
4209 }
4210 }
4211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 private final class AppDirObserver extends FileObserver {
4213 public AppDirObserver(String path, int mask, boolean isrom) {
4214 super(path, mask);
4215 mRootDir = path;
4216 mIsRom = isrom;
4217 }
4218
4219 public void onEvent(int event, String path) {
4220 String removedPackage = null;
4221 int removedUid = -1;
4222 String addedPackage = null;
4223 int addedUid = -1;
4224
4225 synchronized (mInstallLock) {
4226 String fullPathStr = null;
4227 File fullPath = null;
4228 if (path != null) {
4229 fullPath = new File(mRootDir, path);
4230 fullPathStr = fullPath.getPath();
4231 }
4232
4233 if (Config.LOGV) Log.v(
4234 TAG, "File " + fullPathStr + " changed: "
4235 + Integer.toHexString(event));
4236
4237 if (!isPackageFilename(path)) {
4238 if (Config.LOGV) Log.v(
4239 TAG, "Ignoring change of non-package file: " + fullPathStr);
4240 return;
4241 }
4242
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004243 // Ignore packages that are being installed or
4244 // have just been installed.
4245 if (ignoreCodePath(fullPathStr)) {
4246 return;
4247 }
4248 PackageParser.Package p = null;
4249 synchronized (mPackages) {
4250 p = mAppDirs.get(fullPathStr);
4251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004253 if (p != null) {
4254 removePackageLI(p, true);
4255 removedPackage = p.applicationInfo.packageName;
4256 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 }
4258 }
4259
4260 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004262 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4264 PackageParser.PARSE_CHATTY |
4265 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004266 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 if (p != null) {
4268 synchronized (mPackages) {
4269 grantPermissionsLP(p, false);
4270 }
4271 addedPackage = p.applicationInfo.packageName;
4272 addedUid = p.applicationInfo.uid;
4273 }
4274 }
4275 }
4276
4277 synchronized (mPackages) {
4278 mSettings.writeLP();
4279 }
4280 }
4281
4282 if (removedPackage != null) {
4283 Bundle extras = new Bundle(1);
4284 extras.putInt(Intent.EXTRA_UID, removedUid);
4285 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4286 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4287 }
4288 if (addedPackage != null) {
4289 Bundle extras = new Bundle(1);
4290 extras.putInt(Intent.EXTRA_UID, addedUid);
4291 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4292 }
4293 }
4294
4295 private final String mRootDir;
4296 private final boolean mIsRom;
4297 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 /* Called when a downloaded package installation has been confirmed by the user */
4300 public void installPackage(
4301 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004302 installPackage(packageURI, observer, flags, null);
4303 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004304
Jacek Surazski65e13172009-04-28 15:26:38 +02004305 /* Called when a downloaded package installation has been confirmed by the user */
4306 public void installPackage(
4307 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4308 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 mContext.enforceCallingOrSelfPermission(
4310 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004311
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004312 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004313 msg.obj = new InstallParams(packageURI, observer, flags,
4314 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004315 mHandler.sendMessage(msg);
4316 }
4317
Christopher Tate1bb69062010-02-19 17:02:12 -08004318 public void finishPackageInstall(int token) {
4319 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4320 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4321 mHandler.sendMessage(msg);
4322 }
4323
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004324 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 // Queue up an async operation since the package installation may take a little while.
4326 mHandler.post(new Runnable() {
4327 public void run() {
4328 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004329 // Result object to be returned
4330 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004331 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004332 res.uid = -1;
4333 res.pkg = null;
4334 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004335 args.doPreInstall(res.returnCode);
4336 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004337 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004338 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004339 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004340 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004342
4343 // A restore should be performed at this point if (a) the install
4344 // succeeded, (b) the operation is not an update, and (c) the new
4345 // package has a backupAgent defined.
4346 final boolean update = res.removedInfo.removedPackage != null;
4347 boolean doRestore = (!update && res.pkg.applicationInfo.backupAgentName != null);
4348
4349 // Set up the post-install work request bookkeeping. This will be used
4350 // and cleaned up by the post-install event handling regardless of whether
4351 // there's a restore pass performed. Token values are >= 1.
4352 int token;
4353 if (mNextInstallToken < 0) mNextInstallToken = 1;
4354 token = mNextInstallToken++;
4355
4356 PostInstallData data = new PostInstallData(args, res);
4357 mRunningInstalls.put(token, data);
4358 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4359
4360 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4361 // Pass responsibility to the Backup Manager. It will perform a
4362 // restore if appropriate, then pass responsibility back to the
4363 // Package Manager to run the post-install observer callbacks
4364 // and broadcasts.
4365 IBackupManager bm = IBackupManager.Stub.asInterface(
4366 ServiceManager.getService(Context.BACKUP_SERVICE));
4367 if (bm != null) {
4368 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4369 + " to BM for possible restore");
4370 try {
4371 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4372 } catch (RemoteException e) {
4373 // can't happen; the backup manager is local
4374 } catch (Exception e) {
4375 Log.e(TAG, "Exception trying to enqueue restore", e);
4376 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004377 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004378 } else {
4379 Log.e(TAG, "Backup Manager not found!");
4380 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004383
4384 if (!doRestore) {
4385 // No restore possible, or the Backup Manager was mysteriously not
4386 // available -- just fire the post-install work request directly.
4387 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4388 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4389 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 }
4392 });
4393 }
4394
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004395 interface HandlerParams {
4396 void handleStartCopy(IMediaContainerService imcs);
4397 void handleServiceError();
4398 }
4399
4400 class InstallParams implements HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004401 final IPackageInstallObserver observer;
4402 int flags;
4403 final Uri packageURI;
4404 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004405 private InstallArgs mArgs;
4406 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004407 InstallParams(Uri packageURI,
4408 IPackageInstallObserver observer, int flags,
4409 String installerPackageName) {
4410 this.packageURI = packageURI;
4411 this.flags = flags;
4412 this.observer = observer;
4413 this.installerPackageName = installerPackageName;
4414 }
4415
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004416 private int getInstallLocation(IMediaContainerService imcs) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004417 try {
4418 return imcs.getRecommendedInstallLocation(packageURI);
4419 } catch (RemoteException e) {
4420 }
4421 return -1;
4422 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004423
4424 public void handleStartCopy(IMediaContainerService imcs) {
4425 int ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4426 if (imcs != null) {
4427 // Remote call to find out default install location
4428 int loc = getInstallLocation(imcs);
4429 // Use install location to create InstallArgs and temporary
4430 // install location
4431 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
4432 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4433 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4434 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4435 } else {
4436 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4437 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4438 // Set the flag to install on external media.
4439 flags |= PackageManager.INSTALL_EXTERNAL;
4440 } else {
4441 // Make sure the flag for installing on external
4442 // media is unset
4443 flags &= ~PackageManager.INSTALL_EXTERNAL;
4444 }
4445 }
4446 // Disable forward locked apps on sdcard.
4447 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0 &&
4448 (flags & PackageManager.INSTALL_EXTERNAL) != 0) {
4449 // Make sure forward locked apps can only be installed
4450 // on internal storage
4451 Log.w(TAG, "Cannot install protected apps on sdcard");
4452 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4453 } else {
4454 ret = PackageManager.INSTALL_SUCCEEDED;
4455 }
4456 }
4457 }
4458 // Create the file args now.
4459 mArgs = createInstallArgs(this);
4460 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4461 // Create copy only if we are not in an erroneous state.
4462 // Remote call to initiate copy using temporary file
4463 ret = mArgs.copyApk(imcs, true);
4464 }
4465 mRet = ret;
4466 mHandler.sendEmptyMessage(MCS_UNBIND);
4467 handleReturnCode();
4468 }
4469
4470 void handleReturnCode() {
4471 processPendingInstall(mArgs, mRet);
4472 }
4473
4474 public void handleServiceError() {
4475 mArgs = createInstallArgs(this);
4476 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4477 handleReturnCode();
4478 }
4479 };
4480
4481 /*
4482 * Utility class used in movePackage api.
4483 * srcArgs and targetArgs are not set for invalid flags and make
4484 * sure to do null checks when invoking methods on them.
4485 * We probably want to return ErrorPrams for both failed installs
4486 * and moves.
4487 */
4488 class MoveParams implements HandlerParams {
4489 final IPackageMoveObserver observer;
4490 final int flags;
4491 final String packageName;
4492 final InstallArgs srcArgs;
4493 final InstallArgs targetArgs;
4494 int mRet;
4495 MoveParams(InstallArgs srcArgs,
4496 IPackageMoveObserver observer,
4497 int flags, String packageName) {
4498 this.srcArgs = srcArgs;
4499 this.observer = observer;
4500 this.flags = flags;
4501 this.packageName = packageName;
4502 if (srcArgs != null) {
4503 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4504 targetArgs = createInstallArgs(packageUri, flags, packageName);
4505 } else {
4506 targetArgs = null;
4507 }
4508 }
4509
4510 public void handleStartCopy(IMediaContainerService imcs) {
4511 // Create the file args now.
4512 mRet = targetArgs.copyApk(imcs, false);
4513 targetArgs.doPreInstall(mRet);
4514 mHandler.sendEmptyMessage(MCS_UNBIND);
4515 handleReturnCode();
4516 }
4517
4518 void handleReturnCode() {
4519 targetArgs.doPostInstall(mRet);
4520 // TODO invoke pending move
4521 processPendingMove(this, mRet);
4522 }
4523
4524 public void handleServiceError() {
4525 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
4526 handleReturnCode();
4527 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004528 };
4529
4530 private InstallArgs createInstallArgs(InstallParams params) {
4531 if (installOnSd(params.flags)) {
4532 return new SdInstallArgs(params);
4533 } else {
4534 return new FileInstallArgs(params);
4535 }
4536 }
4537
4538 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4539 if (installOnSd(flags)) {
4540 return new SdInstallArgs(fullCodePath, fullResourcePath);
4541 } else {
4542 return new FileInstallArgs(fullCodePath, fullResourcePath);
4543 }
4544 }
4545
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004546 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4547 if (installOnSd(flags)) {
4548 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4549 return new SdInstallArgs(packageURI, cid);
4550 } else {
4551 return new FileInstallArgs(packageURI, pkgName);
4552 }
4553 }
4554
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004555 static abstract class InstallArgs {
4556 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004557 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004558 final int flags;
4559 final Uri packageURI;
4560 final String installerPackageName;
4561
4562 InstallArgs(Uri packageURI,
4563 IPackageInstallObserver observer, int flags,
4564 String installerPackageName) {
4565 this.packageURI = packageURI;
4566 this.flags = flags;
4567 this.observer = observer;
4568 this.installerPackageName = installerPackageName;
4569 }
4570
4571 abstract void createCopyFile();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004572 abstract int copyApk(IMediaContainerService imcs, boolean temp);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004573 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004574 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004575 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004576 abstract String getCodePath();
4577 abstract String getResourcePath();
4578 // Need installer lock especially for dex file removal.
4579 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004580 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004581 }
4582
4583 class FileInstallArgs extends InstallArgs {
4584 File installDir;
4585 String codeFileName;
4586 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004587 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004588
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004589 FileInstallArgs(InstallParams params) {
4590 super(params.packageURI, params.observer,
4591 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004592 }
4593
4594 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4595 super(null, null, 0, null);
4596 File codeFile = new File(fullCodePath);
4597 installDir = codeFile.getParentFile();
4598 codeFileName = fullCodePath;
4599 resourceFileName = fullResourcePath;
4600 }
4601
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004602 FileInstallArgs(Uri packageURI, String pkgName) {
4603 super(packageURI, null, 0, null);
4604 boolean fwdLocked = isFwdLocked(flags);
4605 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4606 String apkName = getNextCodePath(null, pkgName, ".apk");
4607 codeFileName = new File(installDir, apkName + ".apk").getPath();
4608 resourceFileName = getResourcePathFromCodePath();
4609 }
4610
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004611 String getCodePath() {
4612 return codeFileName;
4613 }
4614
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004615 void createCopyFile() {
4616 boolean fwdLocked = isFwdLocked(flags);
4617 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4618 codeFileName = createTempPackageFile(installDir).getPath();
4619 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004620 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004621 }
4622
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004623 int copyApk(IMediaContainerService imcs, boolean temp) {
4624 if (temp) {
4625 // Generate temp file name
4626 createCopyFile();
4627 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004628 // Get a ParcelFileDescriptor to write to the output file
4629 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004630 if (!created) {
4631 try {
4632 codeFile.createNewFile();
4633 // Set permissions
4634 if (!setPermissions()) {
4635 // Failed setting permissions.
4636 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4637 }
4638 } catch (IOException e) {
4639 Log.w(TAG, "Failed to create file " + codeFile);
4640 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4641 }
4642 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004643 ParcelFileDescriptor out = null;
4644 try {
4645 out = ParcelFileDescriptor.open(codeFile,
4646 ParcelFileDescriptor.MODE_READ_WRITE);
4647 } catch (FileNotFoundException e) {
4648 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4649 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4650 }
4651 // Copy the resource now
4652 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4653 try {
4654 if (imcs.copyResource(packageURI, out)) {
4655 ret = PackageManager.INSTALL_SUCCEEDED;
4656 }
4657 } catch (RemoteException e) {
4658 } finally {
4659 try { if (out != null) out.close(); } catch (IOException e) {}
4660 }
4661 return ret;
4662 }
4663
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004664 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004665 if (status != PackageManager.INSTALL_SUCCEEDED) {
4666 cleanUp();
4667 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004668 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004669 }
4670
4671 boolean doRename(int status, final String pkgName, String oldCodePath) {
4672 if (status != PackageManager.INSTALL_SUCCEEDED) {
4673 cleanUp();
4674 return false;
4675 } else {
4676 // Rename based on packageName
4677 File codeFile = new File(getCodePath());
4678 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4679 File desFile = new File(installDir, apkName + ".apk");
4680 if (!codeFile.renameTo(desFile)) {
4681 return false;
4682 }
4683 // Reset paths since the file has been renamed.
4684 codeFileName = desFile.getPath();
4685 resourceFileName = getResourcePathFromCodePath();
4686 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004687 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004688 // Failed setting permissions.
4689 return false;
4690 }
4691 return true;
4692 }
4693 }
4694
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004695 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004696 if (status != PackageManager.INSTALL_SUCCEEDED) {
4697 cleanUp();
4698 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004699 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004700 }
4701
4702 String getResourcePath() {
4703 return resourceFileName;
4704 }
4705
4706 String getResourcePathFromCodePath() {
4707 String codePath = getCodePath();
4708 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4709 String apkNameOnly = getApkName(codePath);
4710 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4711 } else {
4712 return codePath;
4713 }
4714 }
4715
4716 private boolean cleanUp() {
4717 boolean ret = true;
4718 String sourceDir = getCodePath();
4719 String publicSourceDir = getResourcePath();
4720 if (sourceDir != null) {
4721 File sourceFile = new File(sourceDir);
4722 if (!sourceFile.exists()) {
4723 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4724 ret = false;
4725 }
4726 // Delete application's code and resources
4727 sourceFile.delete();
4728 }
4729 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4730 final File publicSourceFile = new File(publicSourceDir);
4731 if (!publicSourceFile.exists()) {
4732 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4733 }
4734 if (publicSourceFile.exists()) {
4735 publicSourceFile.delete();
4736 }
4737 }
4738 return ret;
4739 }
4740
4741 void cleanUpResourcesLI() {
4742 String sourceDir = getCodePath();
4743 if (cleanUp() && mInstaller != null) {
4744 int retCode = mInstaller.rmdex(sourceDir);
4745 if (retCode < 0) {
4746 Log.w(TAG, "Couldn't remove dex file for package: "
4747 + " at location "
4748 + sourceDir + ", retcode=" + retCode);
4749 // we don't consider this to be a failure of the core package deletion
4750 }
4751 }
4752 }
4753
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004754 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004755 // TODO Do this in a more elegant way later on. for now just a hack
4756 if (!isFwdLocked(flags)) {
4757 final int filePermissions =
4758 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4759 |FileUtils.S_IROTH;
4760 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4761 if (retCode != 0) {
4762 Log.e(TAG, "Couldn't set new package file permissions for " +
4763 getCodePath()
4764 + ". The return code was: " + retCode);
4765 // TODO Define new internal error
4766 return false;
4767 }
4768 return true;
4769 }
4770 return true;
4771 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004772
4773 boolean doPostDeleteLI(boolean delete) {
4774 cleanUpResourcesLI();
4775 return true;
4776 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004777 }
4778
4779 class SdInstallArgs extends InstallArgs {
4780 String cid;
4781 String cachePath;
4782 static final String RES_FILE_NAME = "pkg.apk";
4783
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004784 SdInstallArgs(InstallParams params) {
4785 super(params.packageURI, params.observer,
4786 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004787 }
4788
4789 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004791 // Extract cid from fullCodePath
4792 int eidx = fullCodePath.lastIndexOf("/");
4793 String subStr1 = fullCodePath.substring(0, eidx);
4794 int sidx = subStr1.lastIndexOf("/");
4795 cid = subStr1.substring(sidx+1, eidx);
4796 cachePath = subStr1;
4797 }
4798
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004799 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
4801 this.cid = cid;
4802 }
4803
4804 SdInstallArgs(Uri packageURI, String cid) {
4805 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004806 this.cid = cid;
4807 }
4808
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004809 void createCopyFile() {
4810 cid = getTempContainerId();
4811 }
4812
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 int copyApk(IMediaContainerService imcs, boolean temp) {
4814 if (temp) {
4815 createCopyFile();
4816 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004817 try {
4818 cachePath = imcs.copyResourceToContainer(
4819 packageURI, cid,
4820 getEncryptKey(), RES_FILE_NAME);
4821 } catch (RemoteException e) {
4822 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004823 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4824 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004825 }
4826
4827 @Override
4828 String getCodePath() {
4829 return cachePath + "/" + RES_FILE_NAME;
4830 }
4831
4832 @Override
4833 String getResourcePath() {
4834 return cachePath + "/" + RES_FILE_NAME;
4835 }
4836
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004837 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004838 if (status != PackageManager.INSTALL_SUCCEEDED) {
4839 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004840 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004841 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004842 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004843 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004844 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004845 if (cachePath == null) {
4846 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4847 }
4848 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004849 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004850 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004851 }
4852
4853 boolean doRename(int status, final String pkgName,
4854 String oldCodePath) {
4855 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004856 String newCachePath = null;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004857 final int RENAME_FAILED = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004858 final int MOUNT_FAILED = 2;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004859 final int PASS = 4;
4860 int errCode = RENAME_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004861 String errMsg = "RENAME_FAILED";
4862 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004863 if (mounted) {
4864 // Unmount the container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004865 if (!PackageHelper.unMountSdDir(cid)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004866 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4867 return false;
4868 }
4869 mounted = false;
4870 }
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004871 if (PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004872 errCode = MOUNT_FAILED;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004873 errMsg = "MOUNT_FAILED";
4874 if ((newCachePath = PackageHelper.mountSdDir(newCacheId,
4875 getEncryptKey(), Process.SYSTEM_UID)) != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004876 errCode = PASS;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004877 errMsg = "PASS";
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004878 }
4879 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004880 if (errCode != PASS) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004881 Log.i(TAG, "Failed to rename " + cid + " to " + newCacheId +
4882 " at path: " + cachePath + " to new path: " + newCachePath +
4883 "err = " + errMsg);
4884 // Mount old container?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004885 return false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004886 } else {
4887 Log.i(TAG, "Succesfully renamed " + cid + " to " + newCacheId +
4888 " at path: " + cachePath + " to new path: " + newCachePath);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004889 }
4890 cid = newCacheId;
4891 cachePath = newCachePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004892 return true;
4893 }
4894
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004895 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004896 if (status != PackageManager.INSTALL_SUCCEEDED) {
4897 cleanUp();
4898 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004899 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004900 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004901 PackageHelper.mountSdDir(cid,
4902 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004903 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004904 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004905 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 }
4907
4908 private void cleanUp() {
4909 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004910 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004911 }
4912
4913 void cleanUpResourcesLI() {
4914 String sourceFile = getCodePath();
4915 // Remove dex file
4916 if (mInstaller != null) {
4917 int retCode = mInstaller.rmdex(sourceFile.toString());
4918 if (retCode < 0) {
4919 Log.w(TAG, "Couldn't remove dex file for package: "
4920 + " at location "
4921 + sourceFile.toString() + ", retcode=" + retCode);
4922 // we don't consider this to be a failure of the core package deletion
4923 }
4924 }
4925 cleanUp();
4926 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004927
4928 boolean matchContainer(String app) {
4929 if (cid.startsWith(app)) {
4930 return true;
4931 }
4932 return false;
4933 }
4934
4935 String getPackageName() {
4936 int idx = cid.lastIndexOf("-");
4937 if (idx == -1) {
4938 return cid;
4939 }
4940 return cid.substring(0, idx);
4941 }
4942
4943 boolean doPostDeleteLI(boolean delete) {
4944 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004945 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004946 if (mounted) {
4947 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004948 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004949 }
4950 if (ret && delete) {
4951 cleanUpResourcesLI();
4952 }
4953 return ret;
4954 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004955 };
4956
4957 // Utility method used to create code paths based on package name and available index.
4958 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4959 String idxStr = "";
4960 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004961 // Fall back to default value of idx=1 if prefix is not
4962 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004963 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004964 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004965 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004966 if (subStr.endsWith(suffix)) {
4967 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004968 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004969 // If oldCodePath already contains prefix find out the
4970 // ending index to either increment or decrement.
4971 int sidx = subStr.lastIndexOf(prefix);
4972 if (sidx != -1) {
4973 subStr = subStr.substring(sidx + prefix.length());
4974 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004975 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
4976 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004978 try {
4979 idx = Integer.parseInt(subStr);
4980 if (idx <= 1) {
4981 idx++;
4982 } else {
4983 idx--;
4984 }
4985 } catch(NumberFormatException e) {
4986 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 }
4988 }
4989 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 return prefix + idxStr;
4992 }
4993
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004994 // Utility method used to ignore ADD/REMOVE events
4995 // by directory observer.
4996 private static boolean ignoreCodePath(String fullPathStr) {
4997 String apkName = getApkName(fullPathStr);
4998 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
4999 if (idx != -1 && ((idx+1) < apkName.length())) {
5000 // Make sure the package ends with a numeral
5001 String version = apkName.substring(idx+1);
5002 try {
5003 Integer.parseInt(version);
5004 return true;
5005 } catch (NumberFormatException e) {}
5006 }
5007 return false;
5008 }
5009
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005010 // Utility method that returns the relative package path with respect
5011 // to the installation directory. Like say for /data/data/com.test-1.apk
5012 // string com.test-1 is returned.
5013 static String getApkName(String codePath) {
5014 if (codePath == null) {
5015 return null;
5016 }
5017 int sidx = codePath.lastIndexOf("/");
5018 int eidx = codePath.lastIndexOf(".");
5019 if (eidx == -1) {
5020 eidx = codePath.length();
5021 } else if (eidx == 0) {
5022 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5023 return null;
5024 }
5025 return codePath.substring(sidx+1, eidx);
5026 }
5027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 class PackageInstalledInfo {
5029 String name;
5030 int uid;
5031 PackageParser.Package pkg;
5032 int returnCode;
5033 PackageRemovedInfo removedInfo;
5034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005036 /*
5037 * Install a non-existing package.
5038 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005039 private void installNewPackageLI(PackageParser.Package pkg,
5040 int parseFlags,
5041 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005042 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08005044 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005045 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005046
5047 if (useEncryptedFilesystemForPackage(pkg)) {
5048 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
5049 } else {
5050 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
5051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 res.name = pkgName;
5053 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005054 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005056 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 + " without first uninstalling.");
5058 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5059 return;
5060 }
5061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005063 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005065 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5067 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5068 }
5069 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005070 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005071 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 res);
5073 // delete the partially installed application. the data directory will have to be
5074 // restored if it was already existing
5075 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5076 // remove package from internal structures. Note that we want deletePackageX to
5077 // delete the package data and cache directories that it created in
5078 // scanPackageLocked, unless those directories existed before we even tried to
5079 // install.
5080 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005081 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5083 res.removedInfo);
5084 }
5085 }
5086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005087
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005088 private void replacePackageLI(PackageParser.Package pkg,
5089 int parseFlags,
5090 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005091 String installerPackageName, PackageInstalledInfo res) {
5092
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005093 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005094 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 // First find the old package info and check signatures
5096 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005097 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005098 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005099 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005100 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5101 return;
5102 }
5103 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005104 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005105 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005106 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005108 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 }
5110 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005113 PackageParser.Package pkg,
5114 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005115 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 PackageParser.Package newPackage = null;
5117 String pkgName = deletedPackage.packageName;
5118 boolean deletedPkg = true;
5119 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005120
Jacek Surazski65e13172009-04-28 15:26:38 +02005121 String oldInstallerPackageName = null;
5122 synchronized (mPackages) {
5123 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5124 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005125
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005126 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 res.removedInfo)) {
5130 // If the existing package was'nt successfully deleted
5131 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5132 deletedPkg = false;
5133 } else {
5134 // Successfully deleted the old package. Now proceed with re-installation
5135 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005136 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005138 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5140 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005141 }
5142 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005143 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005144 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 res);
5146 updatedSettings = true;
5147 }
5148 }
5149
5150 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5151 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005152 // were keeping around in case we needed them (see below) can now be deleted.
5153 // This info will be set on the res.removedInfo to clean up later on as post
5154 // install action.
5155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 //update signature on the new package setting
5157 //this should always succeed, since we checked the
5158 //signature earlier.
5159 synchronized(mPackages) {
5160 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5161 parseFlags, true);
5162 }
5163 } else {
5164 // remove package from internal structures. Note that we want deletePackageX to
5165 // delete the package data and cache directories that it created in
5166 // scanPackageLocked, unless those directories existed before we even tried to
5167 // install.
5168 if(updatedSettings) {
5169 deletePackageLI(
5170 pkgName, true,
5171 PackageManager.DONT_DELETE_DATA,
5172 res.removedInfo);
5173 }
5174 // Since we failed to install the new package we need to restore the old
5175 // package that we deleted.
5176 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005177 File restoreFile = new File(deletedPackage.mPath);
5178 if (restoreFile == null) {
5179 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5180 return;
5181 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005182 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5183 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005184 // Parse old package
5185 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5186 scanPackageLI(restoreFile, parseFlags, scanMode);
5187 synchronized (mPackages) {
5188 grantPermissionsLP(deletedPackage, false);
5189 mSettings.writeLP();
5190 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005191 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5192 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005194 }
5195 }
5196 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005199 PackageParser.Package pkg,
5200 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005201 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 PackageParser.Package newPackage = null;
5203 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005204 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 PackageParser.PARSE_IS_SYSTEM;
5206 String packageName = deletedPackage.packageName;
5207 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5208 if (packageName == null) {
5209 Log.w(TAG, "Attempt to delete null packageName.");
5210 return;
5211 }
5212 PackageParser.Package oldPkg;
5213 PackageSetting oldPkgSetting;
5214 synchronized (mPackages) {
5215 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005216 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5218 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005219 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 return;
5221 }
5222 }
5223 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5224 res.removedInfo.removedPackage = packageName;
5225 // Remove existing system package
5226 removePackageLI(oldPkg, true);
5227 synchronized (mPackages) {
5228 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5229 }
5230
5231 // Successfully disabled the old package. Now proceed with re-installation
5232 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5233 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005234 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005236 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5238 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5239 }
5240 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005241 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 updatedSettings = true;
5243 }
5244
5245 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5246 //update signature on the new package setting
5247 //this should always succeed, since we checked the
5248 //signature earlier.
5249 synchronized(mPackages) {
5250 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5251 parseFlags, true);
5252 }
5253 } else {
5254 // Re installation failed. Restore old information
5255 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005256 if (newPackage != null) {
5257 removePackageLI(newPackage, true);
5258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005259 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005260 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005262 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 // Restore the old system information in Settings
5264 synchronized(mPackages) {
5265 if(updatedSettings) {
5266 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005267 mSettings.setInstallerPackageName(packageName,
5268 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 }
5270 mSettings.writeLP();
5271 }
5272 }
5273 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005274
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005275 // Utility method used to move dex files during install.
5276 private int moveDexFiles(PackageParser.Package newPackage) {
5277 int retCode;
5278 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5279 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5280 if (retCode != 0) {
5281 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5282 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5283 }
5284 }
5285 return PackageManager.INSTALL_SUCCEEDED;
5286 }
5287
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005288 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005289 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005290 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 synchronized (mPackages) {
5292 //write settings. the installStatus will be incomplete at this stage.
5293 //note that the new package setting would have already been
5294 //added to mPackages. It hasn't been persisted yet.
5295 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5296 mSettings.writeLP();
5297 }
5298
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005299 if ((res.returnCode = moveDexFiles(newPackage))
5300 != PackageManager.INSTALL_SUCCEEDED) {
5301 // Discontinue if moving dex files failed.
5302 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005304 if((res.returnCode = setPermissionsLI(newPackage))
5305 != PackageManager.INSTALL_SUCCEEDED) {
5306 if (mInstaller != null) {
5307 mInstaller.rmdex(newPackage.mScanPath);
5308 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005309 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005310 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 synchronized (mPackages) {
5314 grantPermissionsLP(newPackage, true);
5315 res.name = pkgName;
5316 res.uid = newPackage.applicationInfo.uid;
5317 res.pkg = newPackage;
5318 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005319 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5321 //to update install status
5322 mSettings.writeLP();
5323 }
5324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005325
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005326 private void installPackageLI(InstallArgs args,
5327 boolean newInstall, PackageInstalledInfo res) {
5328 int pFlags = args.flags;
5329 String installerPackageName = args.installerPackageName;
5330 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005331 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005332 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005333 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005334 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5335 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005336 // Result object to be returned
5337 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5338
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005339 // Retrieve PackageSettings and parse package
5340 int parseFlags = PackageParser.PARSE_CHATTY |
5341 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5342 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5343 parseFlags |= mDefParseFlags;
5344 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5345 pp.setSeparateProcesses(mSeparateProcesses);
5346 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5347 null, mMetrics, parseFlags);
5348 if (pkg == null) {
5349 res.returnCode = pp.getParseError();
5350 return;
5351 }
5352 String pkgName = res.name = pkg.packageName;
5353 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5354 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5355 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5356 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005358 }
5359 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5360 res.returnCode = pp.getParseError();
5361 return;
5362 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005363 // Get rid of all references to package scan path via parser.
5364 pp = null;
5365 String oldCodePath = null;
5366 boolean systemApp = false;
5367 synchronized (mPackages) {
5368 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005369 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5370 String oldName = mSettings.mRenamedPackages.get(pkgName);
5371 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5372 && mPackages.containsKey(oldName)) {
5373 // This package is derived from an original package,
5374 // and this device has been updating from that original
5375 // name. We must continue using the original name, so
5376 // rename the new package here.
5377 pkg.setPackageName(pkg.mOriginalPackage);
5378 pkgName = pkg.packageName;
5379 replace = true;
5380 } else if (mPackages.containsKey(pkgName)) {
5381 // This package, under its official name, already exists
5382 // on the device; we should replace it.
5383 replace = true;
5384 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005385 }
5386 PackageSetting ps = mSettings.mPackages.get(pkgName);
5387 if (ps != null) {
5388 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5389 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5390 systemApp = (ps.pkg.applicationInfo.flags &
5391 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005392 }
5393 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005394 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005395
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005396 if (systemApp && onSd) {
5397 // Disable updates to system apps on sdcard
5398 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5399 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5400 return;
5401 }
5402 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5403 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5404 return;
5405 }
5406 // Set application objects path explicitly after the rename
5407 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005408 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005409 replacePackageLI(pkg, parseFlags, scanMode,
5410 installerPackageName, res);
5411 } else {
5412 installNewPackageLI(pkg, parseFlags, scanMode,
5413 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 }
5415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005416
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005417 private int setPermissionsLI(PackageParser.Package newPackage) {
5418 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005419 int retCode = 0;
5420 // TODO Gross hack but fix later. Ideally move this to be a post installation
5421 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005422 if ((newPackage.applicationInfo.flags
5423 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5424 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 try {
5426 extractPublicFiles(newPackage, destResourceFile);
5427 } catch (IOException e) {
5428 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5429 " forward-locked app.");
5430 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5431 } finally {
5432 //TODO clean up the extracted public files
5433 }
5434 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005435 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 newPackage.applicationInfo.uid);
5437 } else {
5438 final int filePermissions =
5439 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005440 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 newPackage.applicationInfo.uid);
5442 }
5443 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005444 // The permissions on the resource file was set when it was copied for
5445 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005449 Log.e(TAG, "Couldn't set new package file permissions for " +
5450 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005452 // TODO Define new internal error
5453 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 }
5455 return PackageManager.INSTALL_SUCCEEDED;
5456 }
5457
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005458 private boolean isForwardLocked(PackageParser.Package pkg) {
5459 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 }
5461
5462 private void extractPublicFiles(PackageParser.Package newPackage,
5463 File publicZipFile) throws IOException {
5464 final ZipOutputStream publicZipOutStream =
5465 new ZipOutputStream(new FileOutputStream(publicZipFile));
5466 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5467
5468 // Copy manifest, resources.arsc and res directory to public zip
5469
5470 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5471 while (privateZipEntries.hasMoreElements()) {
5472 final ZipEntry zipEntry = privateZipEntries.nextElement();
5473 final String zipEntryName = zipEntry.getName();
5474 if ("AndroidManifest.xml".equals(zipEntryName)
5475 || "resources.arsc".equals(zipEntryName)
5476 || zipEntryName.startsWith("res/")) {
5477 try {
5478 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5479 } catch (IOException e) {
5480 try {
5481 publicZipOutStream.close();
5482 throw e;
5483 } finally {
5484 publicZipFile.delete();
5485 }
5486 }
5487 }
5488 }
5489
5490 publicZipOutStream.close();
5491 FileUtils.setPermissions(
5492 publicZipFile.getAbsolutePath(),
5493 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5494 -1, -1);
5495 }
5496
5497 private static void copyZipEntry(ZipEntry zipEntry,
5498 ZipFile inZipFile,
5499 ZipOutputStream outZipStream) throws IOException {
5500 byte[] buffer = new byte[4096];
5501 int num;
5502
5503 ZipEntry newEntry;
5504 if (zipEntry.getMethod() == ZipEntry.STORED) {
5505 // Preserve the STORED method of the input entry.
5506 newEntry = new ZipEntry(zipEntry);
5507 } else {
5508 // Create a new entry so that the compressed len is recomputed.
5509 newEntry = new ZipEntry(zipEntry.getName());
5510 }
5511 outZipStream.putNextEntry(newEntry);
5512
5513 InputStream data = inZipFile.getInputStream(zipEntry);
5514 while ((num = data.read(buffer)) > 0) {
5515 outZipStream.write(buffer, 0, num);
5516 }
5517 outZipStream.flush();
5518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 private void deleteTempPackageFiles() {
5521 FilenameFilter filter = new FilenameFilter() {
5522 public boolean accept(File dir, String name) {
5523 return name.startsWith("vmdl") && name.endsWith(".tmp");
5524 }
5525 };
5526 String tmpFilesList[] = mAppInstallDir.list(filter);
5527 if(tmpFilesList == null) {
5528 return;
5529 }
5530 for(int i = 0; i < tmpFilesList.length; i++) {
5531 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5532 tmpFile.delete();
5533 }
5534 }
5535
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005536 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 File tmpPackageFile;
5538 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005539 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 } catch (IOException e) {
5541 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5542 return null;
5543 }
5544 try {
5545 FileUtils.setPermissions(
5546 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5547 -1, -1);
5548 } catch (IOException e) {
5549 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5550 return null;
5551 }
5552 return tmpPackageFile;
5553 }
5554
5555 public void deletePackage(final String packageName,
5556 final IPackageDeleteObserver observer,
5557 final int flags) {
5558 mContext.enforceCallingOrSelfPermission(
5559 android.Manifest.permission.DELETE_PACKAGES, null);
5560 // Queue up an async operation since the package deletion may take a little while.
5561 mHandler.post(new Runnable() {
5562 public void run() {
5563 mHandler.removeCallbacks(this);
5564 final boolean succeded = deletePackageX(packageName, true, true, flags);
5565 if (observer != null) {
5566 try {
5567 observer.packageDeleted(succeded);
5568 } catch (RemoteException e) {
5569 Log.i(TAG, "Observer no longer exists.");
5570 } //end catch
5571 } //end if
5572 } //end run
5573 });
5574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 /**
5577 * This method is an internal method that could be get invoked either
5578 * to delete an installed package or to clean up a failed installation.
5579 * After deleting an installed package, a broadcast is sent to notify any
5580 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005581 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 * installation wouldn't have sent the initial broadcast either
5583 * The key steps in deleting a package are
5584 * deleting the package information in internal structures like mPackages,
5585 * deleting the packages base directories through installd
5586 * updating mSettings to reflect current status
5587 * persisting settings for later use
5588 * sending a broadcast if necessary
5589 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5591 boolean deleteCodeAndResources, int flags) {
5592 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005593 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594
5595 synchronized (mInstallLock) {
5596 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005600 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5601 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5602
5603 // If the removed package was a system update, the old system packaged
5604 // was re-enabled; we need to broadcast this information
5605 if (systemUpdate) {
5606 Bundle extras = new Bundle(1);
5607 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5608 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5609
5610 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5611 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005614 // Delete the resources here after sending the broadcast to let
5615 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005616 if (info.args != null) {
5617 synchronized (mInstallLock) {
5618 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005619 }
5620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 return res;
5622 }
5623
5624 static class PackageRemovedInfo {
5625 String removedPackage;
5626 int uid = -1;
5627 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005628 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005629 // Clean up resources deleted packages.
5630 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 void sendBroadcast(boolean fullRemove, boolean replacing) {
5633 Bundle extras = new Bundle(1);
5634 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5635 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5636 if (replacing) {
5637 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5638 }
5639 if (removedPackage != null) {
5640 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5641 }
5642 if (removedUid >= 0) {
5643 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5644 }
5645 }
5646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 /*
5649 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5650 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005651 * make sure this flag is set for partially installed apps. If not its meaningless to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 * delete a partially installed application.
5653 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005654 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 int flags) {
5656 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005657 if (outInfo != null) {
5658 outInfo.removedPackage = packageName;
5659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 removePackageLI(p, true);
5661 // Retrieve object to delete permissions for shared user later on
5662 PackageSetting deletedPs;
5663 synchronized (mPackages) {
5664 deletedPs = mSettings.mPackages.get(packageName);
5665 }
5666 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005667 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005669 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 if (retCode < 0) {
5671 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5672 + packageName + ", retcode=" + retCode);
5673 // we don't consider this to be a failure of the core package deletion
5674 }
5675 } else {
5676 //for emulator
5677 PackageParser.Package pkg = mPackages.get(packageName);
5678 File dataDir = new File(pkg.applicationInfo.dataDir);
5679 dataDir.delete();
5680 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005681 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005683 if (outInfo != null) {
5684 outInfo.removedUid = mSettings.removePackageLP(packageName);
5685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 }
5687 }
5688 synchronized (mPackages) {
5689 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5690 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005691 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 }
5693 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005694 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 }
5696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 /*
5699 * Tries to delete system package.
5700 */
5701 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005702 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 ApplicationInfo applicationInfo = p.applicationInfo;
5704 //applicable for non-partially installed applications only
5705 if (applicationInfo == null) {
5706 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5707 return false;
5708 }
5709 PackageSetting ps = null;
5710 // Confirm if the system package has been updated
5711 // An updated system app can be deleted. This will also have to restore
5712 // the system pkg from system partition
5713 synchronized (mPackages) {
5714 ps = mSettings.getDisabledSystemPkg(p.packageName);
5715 }
5716 if (ps == null) {
5717 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5718 return false;
5719 } else {
5720 Log.i(TAG, "Deleting system pkg from data partition");
5721 }
5722 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005723 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005724 boolean deleteCodeAndResources = false;
5725 if (ps.versionCode < p.mVersionCode) {
5726 // Delete code and resources for downgrades
5727 deleteCodeAndResources = true;
5728 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5729 flags &= ~PackageManager.DONT_DELETE_DATA;
5730 }
5731 } else {
5732 // Preserve data by setting flag
5733 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5734 flags |= PackageManager.DONT_DELETE_DATA;
5735 }
5736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5738 if (!ret) {
5739 return false;
5740 }
5741 synchronized (mPackages) {
5742 // Reinstate the old system package
5743 mSettings.enableSystemPackageLP(p.packageName);
5744 }
5745 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005746 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005748 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 if (newPkg == null) {
5751 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5752 return false;
5753 }
5754 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005755 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 mSettings.writeLP();
5757 }
5758 return true;
5759 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5762 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5763 ApplicationInfo applicationInfo = p.applicationInfo;
5764 if (applicationInfo == null) {
5765 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5766 return false;
5767 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005768 if (outInfo != null) {
5769 outInfo.uid = applicationInfo.uid;
5770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771
5772 // Delete package data from internal structures and also remove data if flag is set
5773 removePackageDataLI(p, outInfo, flags);
5774
5775 // Delete application code and resources
5776 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005777 // TODO can pick up from PackageSettings as well
5778 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005779 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005780 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5781 PackageManager.INSTALL_FORWARD_LOCK : 0;
5782 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005783 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 }
5785 return true;
5786 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 /*
5789 * This method handles package deletion in general
5790 */
5791 private boolean deletePackageLI(String packageName,
5792 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5793 if (packageName == null) {
5794 Log.w(TAG, "Attempt to delete null packageName.");
5795 return false;
5796 }
5797 PackageParser.Package p;
5798 boolean dataOnly = false;
5799 synchronized (mPackages) {
5800 p = mPackages.get(packageName);
5801 if (p == null) {
5802 //this retrieves partially installed apps
5803 dataOnly = true;
5804 PackageSetting ps = mSettings.mPackages.get(packageName);
5805 if (ps == null) {
5806 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5807 return false;
5808 }
5809 p = ps.pkg;
5810 }
5811 }
5812 if (p == null) {
5813 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5814 return false;
5815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 if (dataOnly) {
5818 // Delete application data first
5819 removePackageDataLI(p, outInfo, flags);
5820 return true;
5821 }
5822 // At this point the package should have ApplicationInfo associated with it
5823 if (p.applicationInfo == null) {
5824 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5825 return false;
5826 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005827 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5829 Log.i(TAG, "Removing system package:"+p.packageName);
5830 // When an updated system application is deleted we delete the existing resources as well and
5831 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005832 ret = deleteSystemPackageLI(p, flags, outInfo);
5833 } else {
5834 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005835 // Kill application pre-emptively especially for apps on sd.
5836 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005837 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005839 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 public void clearApplicationUserData(final String packageName,
5843 final IPackageDataObserver observer) {
5844 mContext.enforceCallingOrSelfPermission(
5845 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5846 // Queue up an async operation since the package deletion may take a little while.
5847 mHandler.post(new Runnable() {
5848 public void run() {
5849 mHandler.removeCallbacks(this);
5850 final boolean succeeded;
5851 synchronized (mInstallLock) {
5852 succeeded = clearApplicationUserDataLI(packageName);
5853 }
5854 if (succeeded) {
5855 // invoke DeviceStorageMonitor's update method to clear any notifications
5856 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5857 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5858 if (dsm != null) {
5859 dsm.updateMemory();
5860 }
5861 }
5862 if(observer != null) {
5863 try {
5864 observer.onRemoveCompleted(packageName, succeeded);
5865 } catch (RemoteException e) {
5866 Log.i(TAG, "Observer no longer exists.");
5867 }
5868 } //end if observer
5869 } //end run
5870 });
5871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 private boolean clearApplicationUserDataLI(String packageName) {
5874 if (packageName == null) {
5875 Log.w(TAG, "Attempt to delete null packageName.");
5876 return false;
5877 }
5878 PackageParser.Package p;
5879 boolean dataOnly = false;
5880 synchronized (mPackages) {
5881 p = mPackages.get(packageName);
5882 if(p == null) {
5883 dataOnly = true;
5884 PackageSetting ps = mSettings.mPackages.get(packageName);
5885 if((ps == null) || (ps.pkg == null)) {
5886 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5887 return false;
5888 }
5889 p = ps.pkg;
5890 }
5891 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005892 boolean useEncryptedFSDir = false;
5893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 if(!dataOnly) {
5895 //need to check this only for fully installed applications
5896 if (p == null) {
5897 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5898 return false;
5899 }
5900 final ApplicationInfo applicationInfo = p.applicationInfo;
5901 if (applicationInfo == null) {
5902 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5903 return false;
5904 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005905 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 }
5907 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005908 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 if (retCode < 0) {
5910 Log.w(TAG, "Couldn't remove cache files for package: "
5911 + packageName);
5912 return false;
5913 }
5914 }
5915 return true;
5916 }
5917
5918 public void deleteApplicationCacheFiles(final String packageName,
5919 final IPackageDataObserver observer) {
5920 mContext.enforceCallingOrSelfPermission(
5921 android.Manifest.permission.DELETE_CACHE_FILES, null);
5922 // Queue up an async operation since the package deletion may take a little while.
5923 mHandler.post(new Runnable() {
5924 public void run() {
5925 mHandler.removeCallbacks(this);
5926 final boolean succeded;
5927 synchronized (mInstallLock) {
5928 succeded = deleteApplicationCacheFilesLI(packageName);
5929 }
5930 if(observer != null) {
5931 try {
5932 observer.onRemoveCompleted(packageName, succeded);
5933 } catch (RemoteException e) {
5934 Log.i(TAG, "Observer no longer exists.");
5935 }
5936 } //end if observer
5937 } //end run
5938 });
5939 }
5940
5941 private boolean deleteApplicationCacheFilesLI(String packageName) {
5942 if (packageName == null) {
5943 Log.w(TAG, "Attempt to delete null packageName.");
5944 return false;
5945 }
5946 PackageParser.Package p;
5947 synchronized (mPackages) {
5948 p = mPackages.get(packageName);
5949 }
5950 if (p == null) {
5951 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5952 return false;
5953 }
5954 final ApplicationInfo applicationInfo = p.applicationInfo;
5955 if (applicationInfo == null) {
5956 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5957 return false;
5958 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005959 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005961 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 if (retCode < 0) {
5963 Log.w(TAG, "Couldn't remove cache files for package: "
5964 + packageName);
5965 return false;
5966 }
5967 }
5968 return true;
5969 }
5970
5971 public void getPackageSizeInfo(final String packageName,
5972 final IPackageStatsObserver observer) {
5973 mContext.enforceCallingOrSelfPermission(
5974 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5975 // Queue up an async operation since the package deletion may take a little while.
5976 mHandler.post(new Runnable() {
5977 public void run() {
5978 mHandler.removeCallbacks(this);
5979 PackageStats lStats = new PackageStats(packageName);
5980 final boolean succeded;
5981 synchronized (mInstallLock) {
5982 succeded = getPackageSizeInfoLI(packageName, lStats);
5983 }
5984 if(observer != null) {
5985 try {
5986 observer.onGetStatsCompleted(lStats, succeded);
5987 } catch (RemoteException e) {
5988 Log.i(TAG, "Observer no longer exists.");
5989 }
5990 } //end if observer
5991 } //end run
5992 });
5993 }
5994
5995 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5996 if (packageName == null) {
5997 Log.w(TAG, "Attempt to get size of null packageName.");
5998 return false;
5999 }
6000 PackageParser.Package p;
6001 boolean dataOnly = false;
6002 synchronized (mPackages) {
6003 p = mPackages.get(packageName);
6004 if(p == null) {
6005 dataOnly = true;
6006 PackageSetting ps = mSettings.mPackages.get(packageName);
6007 if((ps == null) || (ps.pkg == null)) {
6008 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6009 return false;
6010 }
6011 p = ps.pkg;
6012 }
6013 }
6014 String publicSrcDir = null;
6015 if(!dataOnly) {
6016 final ApplicationInfo applicationInfo = p.applicationInfo;
6017 if (applicationInfo == null) {
6018 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6019 return false;
6020 }
6021 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6022 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006023 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 if (mInstaller != null) {
6025 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006026 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 if (res < 0) {
6028 return false;
6029 } else {
6030 return true;
6031 }
6032 }
6033 return true;
6034 }
6035
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 public void addPackageToPreferred(String packageName) {
6038 mContext.enforceCallingOrSelfPermission(
6039 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006040 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 }
6042
6043 public void removePackageFromPreferred(String packageName) {
6044 mContext.enforceCallingOrSelfPermission(
6045 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006046 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 }
6048
6049 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006050 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 }
6052
6053 public void addPreferredActivity(IntentFilter filter, int match,
6054 ComponentName[] set, ComponentName activity) {
6055 mContext.enforceCallingOrSelfPermission(
6056 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6057
6058 synchronized (mPackages) {
6059 Log.i(TAG, "Adding preferred activity " + activity + ":");
6060 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6061 mSettings.mPreferredActivities.addFilter(
6062 new PreferredActivity(filter, match, set, activity));
6063 mSettings.writeLP();
6064 }
6065 }
6066
Satish Sampath8dbe6122009-06-02 23:35:54 +01006067 public void replacePreferredActivity(IntentFilter filter, int match,
6068 ComponentName[] set, ComponentName activity) {
6069 mContext.enforceCallingOrSelfPermission(
6070 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6071 if (filter.countActions() != 1) {
6072 throw new IllegalArgumentException(
6073 "replacePreferredActivity expects filter to have only 1 action.");
6074 }
6075 if (filter.countCategories() != 1) {
6076 throw new IllegalArgumentException(
6077 "replacePreferredActivity expects filter to have only 1 category.");
6078 }
6079 if (filter.countDataAuthorities() != 0
6080 || filter.countDataPaths() != 0
6081 || filter.countDataSchemes() != 0
6082 || filter.countDataTypes() != 0) {
6083 throw new IllegalArgumentException(
6084 "replacePreferredActivity expects filter to have no data authorities, " +
6085 "paths, schemes or types.");
6086 }
6087 synchronized (mPackages) {
6088 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6089 String action = filter.getAction(0);
6090 String category = filter.getCategory(0);
6091 while (it.hasNext()) {
6092 PreferredActivity pa = it.next();
6093 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6094 it.remove();
6095 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6096 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6097 }
6098 }
6099 addPreferredActivity(filter, match, set, activity);
6100 }
6101 }
6102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 public void clearPackagePreferredActivities(String packageName) {
6104 mContext.enforceCallingOrSelfPermission(
6105 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6106
6107 synchronized (mPackages) {
6108 if (clearPackagePreferredActivitiesLP(packageName)) {
6109 mSettings.writeLP();
6110 }
6111 }
6112 }
6113
6114 boolean clearPackagePreferredActivitiesLP(String packageName) {
6115 boolean changed = false;
6116 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6117 while (it.hasNext()) {
6118 PreferredActivity pa = it.next();
6119 if (pa.mActivity.getPackageName().equals(packageName)) {
6120 it.remove();
6121 changed = true;
6122 }
6123 }
6124 return changed;
6125 }
6126
6127 public int getPreferredActivities(List<IntentFilter> outFilters,
6128 List<ComponentName> outActivities, String packageName) {
6129
6130 int num = 0;
6131 synchronized (mPackages) {
6132 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6133 while (it.hasNext()) {
6134 PreferredActivity pa = it.next();
6135 if (packageName == null
6136 || pa.mActivity.getPackageName().equals(packageName)) {
6137 if (outFilters != null) {
6138 outFilters.add(new IntentFilter(pa));
6139 }
6140 if (outActivities != null) {
6141 outActivities.add(pa.mActivity);
6142 }
6143 }
6144 }
6145 }
6146
6147 return num;
6148 }
6149
6150 public void setApplicationEnabledSetting(String appPackageName,
6151 int newState, int flags) {
6152 setEnabledSetting(appPackageName, null, newState, flags);
6153 }
6154
6155 public void setComponentEnabledSetting(ComponentName componentName,
6156 int newState, int flags) {
6157 setEnabledSetting(componentName.getPackageName(),
6158 componentName.getClassName(), newState, flags);
6159 }
6160
6161 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006162 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6164 || newState == COMPONENT_ENABLED_STATE_ENABLED
6165 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6166 throw new IllegalArgumentException("Invalid new component state: "
6167 + newState);
6168 }
6169 PackageSetting pkgSetting;
6170 final int uid = Binder.getCallingUid();
6171 final int permission = mContext.checkCallingPermission(
6172 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6173 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006174 boolean sendNow = false;
6175 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006176 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006178 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006180 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006182 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006184 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 }
6186 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006187 "Unknown component: " + packageName
6188 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 }
6190 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6191 throw new SecurityException(
6192 "Permission Denial: attempt to change component state from pid="
6193 + Binder.getCallingPid()
6194 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6195 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006196 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 // We're dealing with an application/package level state change
6198 pkgSetting.enabled = newState;
6199 } else {
6200 // We're dealing with a component level state change
6201 switch (newState) {
6202 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006203 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 break;
6205 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006206 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 break;
6208 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006209 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 break;
6211 default:
6212 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006213 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
6215 }
6216 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006217 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006218 components = mPendingBroadcasts.get(packageName);
6219 boolean newPackage = components == null;
6220 if (newPackage) {
6221 components = new ArrayList<String>();
6222 }
6223 if (!components.contains(componentName)) {
6224 components.add(componentName);
6225 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006226 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6227 sendNow = true;
6228 // Purge entry from pending broadcast list if another one exists already
6229 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006230 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006231 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006232 if (newPackage) {
6233 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006234 }
6235 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6236 // Schedule a message
6237 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6238 }
6239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 long callingId = Binder.clearCallingIdentity();
6243 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006244 if (sendNow) {
6245 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006246 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 } finally {
6249 Binder.restoreCallingIdentity(callingId);
6250 }
6251 }
6252
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006253 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006254 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6255 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6256 + " components=" + componentNames);
6257 Bundle extras = new Bundle(4);
6258 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6259 String nameList[] = new String[componentNames.size()];
6260 componentNames.toArray(nameList);
6261 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006262 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6263 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006264 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006265 }
6266
Jacek Surazski65e13172009-04-28 15:26:38 +02006267 public String getInstallerPackageName(String packageName) {
6268 synchronized (mPackages) {
6269 PackageSetting pkg = mSettings.mPackages.get(packageName);
6270 if (pkg == null) {
6271 throw new IllegalArgumentException("Unknown package: " + packageName);
6272 }
6273 return pkg.installerPackageName;
6274 }
6275 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 public int getApplicationEnabledSetting(String appPackageName) {
6278 synchronized (mPackages) {
6279 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6280 if (pkg == null) {
6281 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6282 }
6283 return pkg.enabled;
6284 }
6285 }
6286
6287 public int getComponentEnabledSetting(ComponentName componentName) {
6288 synchronized (mPackages) {
6289 final String packageNameStr = componentName.getPackageName();
6290 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6291 if (pkg == null) {
6292 throw new IllegalArgumentException("Unknown component: " + componentName);
6293 }
6294 final String classNameStr = componentName.getClassName();
6295 return pkg.currentEnabledStateLP(classNameStr);
6296 }
6297 }
6298
6299 public void enterSafeMode() {
6300 if (!mSystemReady) {
6301 mSafeMode = true;
6302 }
6303 }
6304
6305 public void systemReady() {
6306 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006307
6308 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006309 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006310 mContext.getContentResolver(),
6311 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006312 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006313 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006314 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 }
6317
6318 public boolean isSafeMode() {
6319 return mSafeMode;
6320 }
6321
6322 public boolean hasSystemUidErrors() {
6323 return mHasSystemUidErrors;
6324 }
6325
6326 static String arrayToString(int[] array) {
6327 StringBuffer buf = new StringBuffer(128);
6328 buf.append('[');
6329 if (array != null) {
6330 for (int i=0; i<array.length; i++) {
6331 if (i > 0) buf.append(", ");
6332 buf.append(array[i]);
6333 }
6334 }
6335 buf.append(']');
6336 return buf.toString();
6337 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 @Override
6340 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6341 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6342 != PackageManager.PERMISSION_GRANTED) {
6343 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6344 + Binder.getCallingPid()
6345 + ", uid=" + Binder.getCallingUid()
6346 + " without permission "
6347 + android.Manifest.permission.DUMP);
6348 return;
6349 }
6350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 synchronized (mPackages) {
6352 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006353 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 pw.println(" ");
6355 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006356 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 pw.println(" ");
6358 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006359 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 pw.println(" ");
6361 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006362 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 pw.println("Permissions:");
6365 {
6366 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006367 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6368 pw.print(Integer.toHexString(System.identityHashCode(p)));
6369 pw.println("):");
6370 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6371 pw.print(" uid="); pw.print(p.uid);
6372 pw.print(" gids="); pw.print(arrayToString(p.gids));
6373 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 }
6375 }
6376 pw.println(" ");
6377 pw.println("Packages:");
6378 {
6379 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006380 pw.print(" Package [");
6381 pw.print(ps.realName != null ? ps.realName : ps.name);
6382 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006383 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6384 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006385 if (ps.realName != null) {
6386 pw.print(" compat name="); pw.println(ps.name);
6387 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006388 pw.print(" userId="); pw.print(ps.userId);
6389 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6390 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6391 pw.print(" pkg="); pw.println(ps.pkg);
6392 pw.print(" codePath="); pw.println(ps.codePathString);
6393 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006395 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006396 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006397 pw.print(" supportsScreens=[");
6398 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006399 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006400 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006401 if (!first) pw.print(", ");
6402 first = false;
6403 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006404 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006405 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006406 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006407 if (!first) pw.print(", ");
6408 first = false;
6409 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006410 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006411 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006412 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006413 if (!first) pw.print(", ");
6414 first = false;
6415 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006417 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006418 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006419 if (!first) pw.print(", ");
6420 first = false;
6421 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006423 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006424 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6425 if (!first) pw.print(", ");
6426 first = false;
6427 pw.print("anyDensity");
6428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006429 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006430 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006431 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6432 pw.print(" signatures="); pw.println(ps.signatures);
6433 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6434 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6435 pw.print(" installStatus="); pw.print(ps.installStatus);
6436 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 if (ps.disabledComponents.size() > 0) {
6438 pw.println(" disabledComponents:");
6439 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006440 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 }
6442 }
6443 if (ps.enabledComponents.size() > 0) {
6444 pw.println(" enabledComponents:");
6445 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006446 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 }
6448 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006449 if (ps.grantedPermissions.size() > 0) {
6450 pw.println(" grantedPermissions:");
6451 for (String s : ps.grantedPermissions) {
6452 pw.print(" "); pw.println(s);
6453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006455 if (ps.loadedPermissions.size() > 0) {
6456 pw.println(" loadedPermissions:");
6457 for (String s : ps.loadedPermissions) {
6458 pw.print(" "); pw.println(s);
6459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 }
6461 }
6462 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006463 if (mSettings.mRenamedPackages.size() > 0) {
6464 pw.println(" ");
6465 pw.println("Renamed packages:");
6466 for (HashMap.Entry<String, String> e
6467 : mSettings.mRenamedPackages.entrySet()) {
6468 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6469 pw.println(e.getValue());
6470 }
6471 }
6472 if (mSettings.mDisabledSysPackages.size() > 0) {
6473 pw.println(" ");
6474 pw.println("Hidden system packages:");
6475 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6476 pw.print(" Package [");
6477 pw.print(ps.realName != null ? ps.realName : ps.name);
6478 pw.print("] (");
6479 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6480 pw.println("):");
6481 if (ps.realName != null) {
6482 pw.print(" compat name="); pw.println(ps.name);
6483 }
6484 pw.print(" userId="); pw.println(ps.userId);
6485 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6486 pw.print(" codePath="); pw.println(ps.codePathString);
6487 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6488 }
6489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 pw.println(" ");
6491 pw.println("Shared Users:");
6492 {
6493 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006494 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6495 pw.print(Integer.toHexString(System.identityHashCode(su)));
6496 pw.println("):");
6497 pw.print(" userId="); pw.print(su.userId);
6498 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 pw.println(" grantedPermissions:");
6500 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006501 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 }
6503 pw.println(" loadedPermissions:");
6504 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006505 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 }
6507 }
6508 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 pw.println(" ");
6511 pw.println("Settings parse messages:");
6512 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006513
6514 pw.println(" ");
6515 pw.println("Package warning messages:");
6516 File fname = getSettingsProblemFile();
6517 FileInputStream in;
6518 try {
6519 in = new FileInputStream(fname);
6520 int avail = in.available();
6521 byte[] data = new byte[avail];
6522 in.read(data);
6523 pw.println(new String(data));
6524 } catch (FileNotFoundException e) {
6525 } catch (IOException e) {
6526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006528
6529 synchronized (mProviders) {
6530 pw.println(" ");
6531 pw.println("Registered ContentProviders:");
6532 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006533 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006534 pw.println(p.toString());
6535 }
6536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 }
6538
6539 static final class BasePermission {
6540 final static int TYPE_NORMAL = 0;
6541 final static int TYPE_BUILTIN = 1;
6542 final static int TYPE_DYNAMIC = 2;
6543
6544 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006545 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 final int type;
6547 PackageParser.Permission perm;
6548 PermissionInfo pendingInfo;
6549 int uid;
6550 int[] gids;
6551
6552 BasePermission(String _name, String _sourcePackage, int _type) {
6553 name = _name;
6554 sourcePackage = _sourcePackage;
6555 type = _type;
6556 }
6557 }
6558
6559 static class PackageSignatures {
6560 private Signature[] mSignatures;
6561
6562 PackageSignatures(Signature[] sigs) {
6563 assignSignatures(sigs);
6564 }
6565
6566 PackageSignatures() {
6567 }
6568
6569 void writeXml(XmlSerializer serializer, String tagName,
6570 ArrayList<Signature> pastSignatures) throws IOException {
6571 if (mSignatures == null) {
6572 return;
6573 }
6574 serializer.startTag(null, tagName);
6575 serializer.attribute(null, "count",
6576 Integer.toString(mSignatures.length));
6577 for (int i=0; i<mSignatures.length; i++) {
6578 serializer.startTag(null, "cert");
6579 final Signature sig = mSignatures[i];
6580 final int sigHash = sig.hashCode();
6581 final int numPast = pastSignatures.size();
6582 int j;
6583 for (j=0; j<numPast; j++) {
6584 Signature pastSig = pastSignatures.get(j);
6585 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6586 serializer.attribute(null, "index", Integer.toString(j));
6587 break;
6588 }
6589 }
6590 if (j >= numPast) {
6591 pastSignatures.add(sig);
6592 serializer.attribute(null, "index", Integer.toString(numPast));
6593 serializer.attribute(null, "key", sig.toCharsString());
6594 }
6595 serializer.endTag(null, "cert");
6596 }
6597 serializer.endTag(null, tagName);
6598 }
6599
6600 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6601 throws IOException, XmlPullParserException {
6602 String countStr = parser.getAttributeValue(null, "count");
6603 if (countStr == null) {
6604 reportSettingsProblem(Log.WARN,
6605 "Error in package manager settings: <signatures> has"
6606 + " no count at " + parser.getPositionDescription());
6607 XmlUtils.skipCurrentTag(parser);
6608 }
6609 final int count = Integer.parseInt(countStr);
6610 mSignatures = new Signature[count];
6611 int pos = 0;
6612
6613 int outerDepth = parser.getDepth();
6614 int type;
6615 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6616 && (type != XmlPullParser.END_TAG
6617 || parser.getDepth() > outerDepth)) {
6618 if (type == XmlPullParser.END_TAG
6619 || type == XmlPullParser.TEXT) {
6620 continue;
6621 }
6622
6623 String tagName = parser.getName();
6624 if (tagName.equals("cert")) {
6625 if (pos < count) {
6626 String index = parser.getAttributeValue(null, "index");
6627 if (index != null) {
6628 try {
6629 int idx = Integer.parseInt(index);
6630 String key = parser.getAttributeValue(null, "key");
6631 if (key == null) {
6632 if (idx >= 0 && idx < pastSignatures.size()) {
6633 Signature sig = pastSignatures.get(idx);
6634 if (sig != null) {
6635 mSignatures[pos] = pastSignatures.get(idx);
6636 pos++;
6637 } else {
6638 reportSettingsProblem(Log.WARN,
6639 "Error in package manager settings: <cert> "
6640 + "index " + index + " is not defined at "
6641 + parser.getPositionDescription());
6642 }
6643 } else {
6644 reportSettingsProblem(Log.WARN,
6645 "Error in package manager settings: <cert> "
6646 + "index " + index + " is out of bounds at "
6647 + parser.getPositionDescription());
6648 }
6649 } else {
6650 while (pastSignatures.size() <= idx) {
6651 pastSignatures.add(null);
6652 }
6653 Signature sig = new Signature(key);
6654 pastSignatures.set(idx, sig);
6655 mSignatures[pos] = sig;
6656 pos++;
6657 }
6658 } catch (NumberFormatException e) {
6659 reportSettingsProblem(Log.WARN,
6660 "Error in package manager settings: <cert> "
6661 + "index " + index + " is not a number at "
6662 + parser.getPositionDescription());
6663 }
6664 } else {
6665 reportSettingsProblem(Log.WARN,
6666 "Error in package manager settings: <cert> has"
6667 + " no index at " + parser.getPositionDescription());
6668 }
6669 } else {
6670 reportSettingsProblem(Log.WARN,
6671 "Error in package manager settings: too "
6672 + "many <cert> tags, expected " + count
6673 + " at " + parser.getPositionDescription());
6674 }
6675 } else {
6676 reportSettingsProblem(Log.WARN,
6677 "Unknown element under <cert>: "
6678 + parser.getName());
6679 }
6680 XmlUtils.skipCurrentTag(parser);
6681 }
6682
6683 if (pos < count) {
6684 // Should never happen -- there is an error in the written
6685 // settings -- but if it does we don't want to generate
6686 // a bad array.
6687 Signature[] newSigs = new Signature[pos];
6688 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6689 mSignatures = newSigs;
6690 }
6691 }
6692
6693 /**
6694 * If any of the given 'sigs' is contained in the existing signatures,
6695 * then completely replace the current signatures with the ones in
6696 * 'sigs'. This is used for updating an existing package to a newly
6697 * installed version.
6698 */
6699 boolean updateSignatures(Signature[] sigs, boolean update) {
6700 if (mSignatures == null) {
6701 if (update) {
6702 assignSignatures(sigs);
6703 }
6704 return true;
6705 }
6706 if (sigs == null) {
6707 return false;
6708 }
6709
6710 for (int i=0; i<sigs.length; i++) {
6711 Signature sig = sigs[i];
6712 for (int j=0; j<mSignatures.length; j++) {
6713 if (mSignatures[j].equals(sig)) {
6714 if (update) {
6715 assignSignatures(sigs);
6716 }
6717 return true;
6718 }
6719 }
6720 }
6721 return false;
6722 }
6723
6724 /**
6725 * If any of the given 'sigs' is contained in the existing signatures,
6726 * then add in any new signatures found in 'sigs'. This is used for
6727 * including a new package into an existing shared user id.
6728 */
6729 boolean mergeSignatures(Signature[] sigs, boolean update) {
6730 if (mSignatures == null) {
6731 if (update) {
6732 assignSignatures(sigs);
6733 }
6734 return true;
6735 }
6736 if (sigs == null) {
6737 return false;
6738 }
6739
6740 Signature[] added = null;
6741 int addedCount = 0;
6742 boolean haveMatch = false;
6743 for (int i=0; i<sigs.length; i++) {
6744 Signature sig = sigs[i];
6745 boolean found = false;
6746 for (int j=0; j<mSignatures.length; j++) {
6747 if (mSignatures[j].equals(sig)) {
6748 found = true;
6749 haveMatch = true;
6750 break;
6751 }
6752 }
6753
6754 if (!found) {
6755 if (added == null) {
6756 added = new Signature[sigs.length];
6757 }
6758 added[i] = sig;
6759 addedCount++;
6760 }
6761 }
6762
6763 if (!haveMatch) {
6764 // Nothing matched -- reject the new signatures.
6765 return false;
6766 }
6767 if (added == null) {
6768 // Completely matched -- nothing else to do.
6769 return true;
6770 }
6771
6772 // Add additional signatures in.
6773 if (update) {
6774 Signature[] total = new Signature[addedCount+mSignatures.length];
6775 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6776 int j = mSignatures.length;
6777 for (int i=0; i<added.length; i++) {
6778 if (added[i] != null) {
6779 total[j] = added[i];
6780 j++;
6781 }
6782 }
6783 mSignatures = total;
6784 }
6785 return true;
6786 }
6787
6788 private void assignSignatures(Signature[] sigs) {
6789 if (sigs == null) {
6790 mSignatures = null;
6791 return;
6792 }
6793 mSignatures = new Signature[sigs.length];
6794 for (int i=0; i<sigs.length; i++) {
6795 mSignatures[i] = sigs[i];
6796 }
6797 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 @Override
6800 public String toString() {
6801 StringBuffer buf = new StringBuffer(128);
6802 buf.append("PackageSignatures{");
6803 buf.append(Integer.toHexString(System.identityHashCode(this)));
6804 buf.append(" [");
6805 if (mSignatures != null) {
6806 for (int i=0; i<mSignatures.length; i++) {
6807 if (i > 0) buf.append(", ");
6808 buf.append(Integer.toHexString(
6809 System.identityHashCode(mSignatures[i])));
6810 }
6811 }
6812 buf.append("]}");
6813 return buf.toString();
6814 }
6815 }
6816
6817 static class PreferredActivity extends IntentFilter {
6818 final int mMatch;
6819 final String[] mSetPackages;
6820 final String[] mSetClasses;
6821 final String[] mSetComponents;
6822 final ComponentName mActivity;
6823 final String mShortActivity;
6824 String mParseError;
6825
6826 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6827 ComponentName activity) {
6828 super(filter);
6829 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6830 mActivity = activity;
6831 mShortActivity = activity.flattenToShortString();
6832 mParseError = null;
6833 if (set != null) {
6834 final int N = set.length;
6835 String[] myPackages = new String[N];
6836 String[] myClasses = new String[N];
6837 String[] myComponents = new String[N];
6838 for (int i=0; i<N; i++) {
6839 ComponentName cn = set[i];
6840 if (cn == null) {
6841 mSetPackages = null;
6842 mSetClasses = null;
6843 mSetComponents = null;
6844 return;
6845 }
6846 myPackages[i] = cn.getPackageName().intern();
6847 myClasses[i] = cn.getClassName().intern();
6848 myComponents[i] = cn.flattenToShortString().intern();
6849 }
6850 mSetPackages = myPackages;
6851 mSetClasses = myClasses;
6852 mSetComponents = myComponents;
6853 } else {
6854 mSetPackages = null;
6855 mSetClasses = null;
6856 mSetComponents = null;
6857 }
6858 }
6859
6860 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6861 IOException {
6862 mShortActivity = parser.getAttributeValue(null, "name");
6863 mActivity = ComponentName.unflattenFromString(mShortActivity);
6864 if (mActivity == null) {
6865 mParseError = "Bad activity name " + mShortActivity;
6866 }
6867 String matchStr = parser.getAttributeValue(null, "match");
6868 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6869 String setCountStr = parser.getAttributeValue(null, "set");
6870 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6871
6872 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6873 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6874 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6875
6876 int setPos = 0;
6877
6878 int outerDepth = parser.getDepth();
6879 int type;
6880 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6881 && (type != XmlPullParser.END_TAG
6882 || parser.getDepth() > outerDepth)) {
6883 if (type == XmlPullParser.END_TAG
6884 || type == XmlPullParser.TEXT) {
6885 continue;
6886 }
6887
6888 String tagName = parser.getName();
6889 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6890 // + parser.getDepth() + " tag=" + tagName);
6891 if (tagName.equals("set")) {
6892 String name = parser.getAttributeValue(null, "name");
6893 if (name == null) {
6894 if (mParseError == null) {
6895 mParseError = "No name in set tag in preferred activity "
6896 + mShortActivity;
6897 }
6898 } else if (setPos >= setCount) {
6899 if (mParseError == null) {
6900 mParseError = "Too many set tags in preferred activity "
6901 + mShortActivity;
6902 }
6903 } else {
6904 ComponentName cn = ComponentName.unflattenFromString(name);
6905 if (cn == null) {
6906 if (mParseError == null) {
6907 mParseError = "Bad set name " + name + " in preferred activity "
6908 + mShortActivity;
6909 }
6910 } else {
6911 myPackages[setPos] = cn.getPackageName();
6912 myClasses[setPos] = cn.getClassName();
6913 myComponents[setPos] = name;
6914 setPos++;
6915 }
6916 }
6917 XmlUtils.skipCurrentTag(parser);
6918 } else if (tagName.equals("filter")) {
6919 //Log.i(TAG, "Starting to parse filter...");
6920 readFromXml(parser);
6921 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6922 // + parser.getDepth() + " tag=" + parser.getName());
6923 } else {
6924 reportSettingsProblem(Log.WARN,
6925 "Unknown element under <preferred-activities>: "
6926 + parser.getName());
6927 XmlUtils.skipCurrentTag(parser);
6928 }
6929 }
6930
6931 if (setPos != setCount) {
6932 if (mParseError == null) {
6933 mParseError = "Not enough set tags (expected " + setCount
6934 + " but found " + setPos + ") in " + mShortActivity;
6935 }
6936 }
6937
6938 mSetPackages = myPackages;
6939 mSetClasses = myClasses;
6940 mSetComponents = myComponents;
6941 }
6942
6943 public void writeToXml(XmlSerializer serializer) throws IOException {
6944 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6945 serializer.attribute(null, "name", mShortActivity);
6946 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6947 serializer.attribute(null, "set", Integer.toString(NS));
6948 for (int s=0; s<NS; s++) {
6949 serializer.startTag(null, "set");
6950 serializer.attribute(null, "name", mSetComponents[s]);
6951 serializer.endTag(null, "set");
6952 }
6953 serializer.startTag(null, "filter");
6954 super.writeToXml(serializer);
6955 serializer.endTag(null, "filter");
6956 }
6957
6958 boolean sameSet(List<ResolveInfo> query, int priority) {
6959 if (mSetPackages == null) return false;
6960 final int NQ = query.size();
6961 final int NS = mSetPackages.length;
6962 int numMatch = 0;
6963 for (int i=0; i<NQ; i++) {
6964 ResolveInfo ri = query.get(i);
6965 if (ri.priority != priority) continue;
6966 ActivityInfo ai = ri.activityInfo;
6967 boolean good = false;
6968 for (int j=0; j<NS; j++) {
6969 if (mSetPackages[j].equals(ai.packageName)
6970 && mSetClasses[j].equals(ai.name)) {
6971 numMatch++;
6972 good = true;
6973 break;
6974 }
6975 }
6976 if (!good) return false;
6977 }
6978 return numMatch == NS;
6979 }
6980 }
6981
6982 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006983 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006985 HashSet<String> grantedPermissions = new HashSet<String>();
6986 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006991 setFlags(pkgFlags);
6992 }
6993
6994 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006995 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08006996 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6997 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 }
6999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 /**
7002 * Settings base class for pending and resolved classes.
7003 */
7004 static class PackageSettingBase extends GrantedPermissions {
7005 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007006 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007007 File codePath;
7008 String codePathString;
7009 File resourcePath;
7010 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 private long timeStamp;
7012 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007013 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007015 boolean uidError;
7016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 PackageSignatures signatures = new PackageSignatures();
7018
7019 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 /* Explicitly disabled components */
7022 HashSet<String> disabledComponents = new HashSet<String>(0);
7023 /* Explicitly enabled components */
7024 HashSet<String> enabledComponents = new HashSet<String>(0);
7025 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7026 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007027
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007028 PackageSettingBase origPackage;
7029
Jacek Surazski65e13172009-04-28 15:26:38 +02007030 /* package name of the app that installed this package */
7031 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007033 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007034 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 super(pkgFlags);
7036 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007037 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007038 init(codePath, resourcePath, pVersionCode);
7039 }
7040
7041 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 this.codePath = codePath;
7043 this.codePathString = codePath.toString();
7044 this.resourcePath = resourcePath;
7045 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007046 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007048
Jacek Surazski65e13172009-04-28 15:26:38 +02007049 public void setInstallerPackageName(String packageName) {
7050 installerPackageName = packageName;
7051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007052
Jacek Surazski65e13172009-04-28 15:26:38 +02007053 String getInstallerPackageName() {
7054 return installerPackageName;
7055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007057 public void setInstallStatus(int newStatus) {
7058 installStatus = newStatus;
7059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 public int getInstallStatus() {
7062 return installStatus;
7063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 public void setTimeStamp(long newStamp) {
7066 if (newStamp != timeStamp) {
7067 timeStamp = newStamp;
7068 timeStampString = Long.toString(newStamp);
7069 }
7070 }
7071
7072 public void setTimeStamp(long newStamp, String newStampStr) {
7073 timeStamp = newStamp;
7074 timeStampString = newStampStr;
7075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 public long getTimeStamp() {
7078 return timeStamp;
7079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 public String getTimeStampStr() {
7082 return timeStampString;
7083 }
7084
7085 public void copyFrom(PackageSettingBase base) {
7086 grantedPermissions = base.grantedPermissions;
7087 gids = base.gids;
7088 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 timeStamp = base.timeStamp;
7091 timeStampString = base.timeStampString;
7092 signatures = base.signatures;
7093 permissionsFixed = base.permissionsFixed;
7094 disabledComponents = base.disabledComponents;
7095 enabledComponents = base.enabledComponents;
7096 enabled = base.enabled;
7097 installStatus = base.installStatus;
7098 }
7099
7100 void enableComponentLP(String componentClassName) {
7101 disabledComponents.remove(componentClassName);
7102 enabledComponents.add(componentClassName);
7103 }
7104
7105 void disableComponentLP(String componentClassName) {
7106 enabledComponents.remove(componentClassName);
7107 disabledComponents.add(componentClassName);
7108 }
7109
7110 void restoreComponentLP(String componentClassName) {
7111 enabledComponents.remove(componentClassName);
7112 disabledComponents.remove(componentClassName);
7113 }
7114
7115 int currentEnabledStateLP(String componentName) {
7116 if (enabledComponents.contains(componentName)) {
7117 return COMPONENT_ENABLED_STATE_ENABLED;
7118 } else if (disabledComponents.contains(componentName)) {
7119 return COMPONENT_ENABLED_STATE_DISABLED;
7120 } else {
7121 return COMPONENT_ENABLED_STATE_DEFAULT;
7122 }
7123 }
7124 }
7125
7126 /**
7127 * Settings data for a particular package we know about.
7128 */
7129 static final class PackageSetting extends PackageSettingBase {
7130 int userId;
7131 PackageParser.Package pkg;
7132 SharedUserSetting sharedUser;
7133
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007134 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007135 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007136 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007139 @Override
7140 public String toString() {
7141 return "PackageSetting{"
7142 + Integer.toHexString(System.identityHashCode(this))
7143 + " " + name + "/" + userId + "}";
7144 }
7145 }
7146
7147 /**
7148 * Settings data for a particular shared user ID we know about.
7149 */
7150 static final class SharedUserSetting extends GrantedPermissions {
7151 final String name;
7152 int userId;
7153 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7154 final PackageSignatures signatures = new PackageSignatures();
7155
7156 SharedUserSetting(String _name, int _pkgFlags) {
7157 super(_pkgFlags);
7158 name = _name;
7159 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 @Override
7162 public String toString() {
7163 return "SharedUserSetting{"
7164 + Integer.toHexString(System.identityHashCode(this))
7165 + " " + name + "/" + userId + "}";
7166 }
7167 }
7168
7169 /**
7170 * Holds information about dynamic settings.
7171 */
7172 private static final class Settings {
7173 private final File mSettingsFilename;
7174 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007175 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 private final HashMap<String, PackageSetting> mPackages =
7177 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 // List of replaced system applications
7179 final HashMap<String, PackageSetting> mDisabledSysPackages =
7180 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 // The user's preferred activities associated with particular intent
7183 // filters.
7184 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7185 new IntentResolver<PreferredActivity, PreferredActivity>() {
7186 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007187 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007189 out.print(prefix); out.print(
7190 Integer.toHexString(System.identityHashCode(filter)));
7191 out.print(' ');
7192 out.print(filter.mActivity.flattenToShortString());
7193 out.print(" match=0x");
7194 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007196 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007198 out.print(prefix); out.print(" ");
7199 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 }
7201 }
7202 }
7203 };
7204 private final HashMap<String, SharedUserSetting> mSharedUsers =
7205 new HashMap<String, SharedUserSetting>();
7206 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7207 private final SparseArray<Object> mOtherUserIds =
7208 new SparseArray<Object>();
7209
7210 // For reading/writing settings file.
7211 private final ArrayList<Signature> mPastSignatures =
7212 new ArrayList<Signature>();
7213
7214 // Mapping from permission names to info about them.
7215 final HashMap<String, BasePermission> mPermissions =
7216 new HashMap<String, BasePermission>();
7217
7218 // Mapping from permission tree names to info about them.
7219 final HashMap<String, BasePermission> mPermissionTrees =
7220 new HashMap<String, BasePermission>();
7221
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007222 // Packages that have been uninstalled and still need their external
7223 // storage data deleted.
7224 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7225
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007226 // Packages that have been renamed since they were first installed.
7227 // Keys are the new names of the packages, values are the original
7228 // names. The packages appear everwhere else under their original
7229 // names.
7230 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 private final StringBuilder mReadMessages = new StringBuilder();
7233
7234 private static final class PendingPackage extends PackageSettingBase {
7235 final int sharedId;
7236
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007237 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007238 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007239 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007240 this.sharedId = sharedId;
7241 }
7242 }
7243 private final ArrayList<PendingPackage> mPendingPackages
7244 = new ArrayList<PendingPackage>();
7245
7246 Settings() {
7247 File dataDir = Environment.getDataDirectory();
7248 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007249 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7250 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007251 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007252 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007253 FileUtils.setPermissions(systemDir.toString(),
7254 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7255 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7256 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007257 FileUtils.setPermissions(systemSecureDir.toString(),
7258 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7259 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7260 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 mSettingsFilename = new File(systemDir, "packages.xml");
7262 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007263 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007264 }
7265
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007266 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007267 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 int pkgFlags, boolean create, boolean add) {
7269 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007270 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007271 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007272 return p;
7273 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007274
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007275 PackageSetting peekPackageLP(String name) {
7276 return mPackages.get(name);
7277 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 PackageSetting p = mPackages.get(name);
7279 if (p != null && p.codePath.getPath().equals(codePath)) {
7280 return p;
7281 }
7282 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007283 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 void setInstallStatus(String pkgName, int status) {
7287 PackageSetting p = mPackages.get(pkgName);
7288 if(p != null) {
7289 if(p.getInstallStatus() != status) {
7290 p.setInstallStatus(status);
7291 }
7292 }
7293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007294
Jacek Surazski65e13172009-04-28 15:26:38 +02007295 void setInstallerPackageName(String pkgName,
7296 String installerPkgName) {
7297 PackageSetting p = mPackages.get(pkgName);
7298 if(p != null) {
7299 p.setInstallerPackageName(installerPkgName);
7300 }
7301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007302
Jacek Surazski65e13172009-04-28 15:26:38 +02007303 String getInstallerPackageName(String pkgName) {
7304 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007305 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007306 }
7307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 int getInstallStatus(String pkgName) {
7309 PackageSetting p = mPackages.get(pkgName);
7310 if(p != null) {
7311 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 return -1;
7314 }
7315
7316 SharedUserSetting getSharedUserLP(String name,
7317 int pkgFlags, boolean create) {
7318 SharedUserSetting s = mSharedUsers.get(name);
7319 if (s == null) {
7320 if (!create) {
7321 return null;
7322 }
7323 s = new SharedUserSetting(name, pkgFlags);
7324 if (MULTIPLE_APPLICATION_UIDS) {
7325 s.userId = newUserIdLP(s);
7326 } else {
7327 s.userId = FIRST_APPLICATION_UID;
7328 }
7329 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7330 // < 0 means we couldn't assign a userid; fall out and return
7331 // s, which is currently null
7332 if (s.userId >= 0) {
7333 mSharedUsers.put(name, s);
7334 }
7335 }
7336
7337 return s;
7338 }
7339
7340 int disableSystemPackageLP(String name) {
7341 PackageSetting p = mPackages.get(name);
7342 if(p == null) {
7343 Log.w(TAG, "Package:"+name+" is not an installed package");
7344 return -1;
7345 }
7346 PackageSetting dp = mDisabledSysPackages.get(name);
7347 // always make sure the system package code and resource paths dont change
7348 if(dp == null) {
7349 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7350 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7351 }
7352 mDisabledSysPackages.put(name, p);
7353 }
7354 return removePackageLP(name);
7355 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 PackageSetting enableSystemPackageLP(String name) {
7358 PackageSetting p = mDisabledSysPackages.get(name);
7359 if(p == null) {
7360 Log.w(TAG, "Package:"+name+" is not disabled");
7361 return null;
7362 }
7363 // Reset flag in ApplicationInfo object
7364 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7365 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7366 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007367 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007368 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007369 mDisabledSysPackages.remove(name);
7370 return ret;
7371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007372
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007373 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007374 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 PackageSetting p = mPackages.get(name);
7376 if (p != null) {
7377 if (p.userId == uid) {
7378 return p;
7379 }
7380 reportSettingsProblem(Log.ERROR,
7381 "Adding duplicate package, keeping first: " + name);
7382 return null;
7383 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007384 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007385 p.userId = uid;
7386 if (addUserIdLP(uid, p, name)) {
7387 mPackages.put(name, p);
7388 return p;
7389 }
7390 return null;
7391 }
7392
7393 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7394 SharedUserSetting s = mSharedUsers.get(name);
7395 if (s != null) {
7396 if (s.userId == uid) {
7397 return s;
7398 }
7399 reportSettingsProblem(Log.ERROR,
7400 "Adding duplicate shared user, keeping first: " + name);
7401 return null;
7402 }
7403 s = new SharedUserSetting(name, pkgFlags);
7404 s.userId = uid;
7405 if (addUserIdLP(uid, s, name)) {
7406 mSharedUsers.put(name, s);
7407 return s;
7408 }
7409 return null;
7410 }
7411
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007412 // Transfer ownership of permissions from one package to another.
7413 private void transferPermissions(String origPkg, String newPkg) {
7414 // Transfer ownership of permissions to the new package.
7415 for (int i=0; i<2; i++) {
7416 HashMap<String, BasePermission> permissions =
7417 i == 0 ? mPermissionTrees : mPermissions;
7418 for (BasePermission bp : permissions.values()) {
7419 if (origPkg.equals(bp.sourcePackage)) {
7420 if (DEBUG_UPGRADE) Log.v(TAG,
7421 "Moving permission " + bp.name
7422 + " from pkg " + bp.sourcePackage
7423 + " to " + newPkg);
7424 bp.sourcePackage = newPkg;
7425 bp.perm = null;
7426 if (bp.pendingInfo != null) {
7427 bp.sourcePackage = newPkg;
7428 }
7429 bp.uid = 0;
7430 bp.gids = null;
7431 }
7432 }
7433 }
7434 }
7435
7436 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007437 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007438 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 PackageSetting p = mPackages.get(name);
7440 if (p != null) {
7441 if (!p.codePath.equals(codePath)) {
7442 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007443 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007444 // This is an updated system app with versions in both system
7445 // and data partition. Just let the most recent version
7446 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007447 Log.w(TAG, "Trying to update system app code path from " +
7448 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007449 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007450 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007451 reportSettingsProblem(Log.WARN,
7452 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007453 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007455 }
7456 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007457 reportSettingsProblem(Log.WARN,
7458 "Package " + name + " shared user changed from "
7459 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7460 + " to "
7461 + (sharedUser != null ? sharedUser.name : "<nothing>")
7462 + "; replacing with new");
7463 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007464 } else {
7465 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7466 // If what we are scanning is a system package, then
7467 // make it so, regardless of whether it was previously
7468 // installed only in the data partition.
7469 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 }
7472 }
7473 if (p == null) {
7474 // Create a new PackageSettings entry. this can end up here because
7475 // of code path mismatch or user id mismatch of an updated system partition
7476 if (!create) {
7477 return null;
7478 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007479 if (origPackage != null) {
7480 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007481 p = new PackageSetting(origPackage.name, name, codePath,
7482 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007483 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7484 + " is adopting original package " + origPackage.name);
7485 p.copyFrom(origPackage);
7486 p.sharedUser = origPackage.sharedUser;
7487 p.userId = origPackage.userId;
7488 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007489 mRenamedPackages.put(name, origPackage.name);
7490 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007491 // Update new package state.
7492 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007494 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007495 p.setTimeStamp(codePath.lastModified());
7496 p.sharedUser = sharedUser;
7497 if (sharedUser != null) {
7498 p.userId = sharedUser.userId;
7499 } else if (MULTIPLE_APPLICATION_UIDS) {
7500 // Clone the setting here for disabled system packages
7501 PackageSetting dis = mDisabledSysPackages.get(name);
7502 if (dis != null) {
7503 // For disabled packages a new setting is created
7504 // from the existing user id. This still has to be
7505 // added to list of user id's
7506 // Copy signatures from previous setting
7507 if (dis.signatures.mSignatures != null) {
7508 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7509 }
7510 p.userId = dis.userId;
7511 // Clone permissions
7512 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7513 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7514 // Clone component info
7515 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7516 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7517 // Add new setting to list of user ids
7518 addUserIdLP(p.userId, p, name);
7519 } else {
7520 // Assign new user id
7521 p.userId = newUserIdLP(p);
7522 }
7523 } else {
7524 p.userId = FIRST_APPLICATION_UID;
7525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 }
7527 if (p.userId < 0) {
7528 reportSettingsProblem(Log.WARN,
7529 "Package " + name + " could not be assigned a valid uid");
7530 return null;
7531 }
7532 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007533 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007535 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 }
7537 }
7538 return p;
7539 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007540
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007541 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007542 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007543 String codePath = pkg.applicationInfo.sourceDir;
7544 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007545 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007546 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007547 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007548 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007549 p.codePath = new File(codePath);
7550 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007551 }
7552 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007553 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007554 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007555 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007556 p.resourcePath = new File(resourcePath);
7557 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007558 }
7559 // Update version code if needed
7560 if (pkg.mVersionCode != p.versionCode) {
7561 p.versionCode = pkg.mVersionCode;
7562 }
7563 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7564 }
7565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 // Utility method that adds a PackageSetting to mPackages and
7567 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007568 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 SharedUserSetting sharedUser) {
7570 mPackages.put(name, p);
7571 if (sharedUser != null) {
7572 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7573 reportSettingsProblem(Log.ERROR,
7574 "Package " + p.name + " was user "
7575 + p.sharedUser + " but is now " + sharedUser
7576 + "; I am not changing its files so it will probably fail!");
7577 p.sharedUser.packages.remove(p);
7578 } else if (p.userId != sharedUser.userId) {
7579 reportSettingsProblem(Log.ERROR,
7580 "Package " + p.name + " was user id " + p.userId
7581 + " but is now user " + sharedUser
7582 + " with id " + sharedUser.userId
7583 + "; I am not changing its files so it will probably fail!");
7584 }
7585
7586 sharedUser.packages.add(p);
7587 p.sharedUser = sharedUser;
7588 p.userId = sharedUser.userId;
7589 }
7590 }
7591
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007592 /*
7593 * Update the shared user setting when a package using
7594 * specifying the shared user id is removed. The gids
7595 * associated with each permission of the deleted package
7596 * are removed from the shared user's gid list only if its
7597 * not in use by other permissions of packages in the
7598 * shared user setting.
7599 */
7600 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7602 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7603 return;
7604 }
7605 // No sharedUserId
7606 if (deletedPs.sharedUser == null) {
7607 return;
7608 }
7609 SharedUserSetting sus = deletedPs.sharedUser;
7610 // Update permissions
7611 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7612 boolean used = false;
7613 if (!sus.grantedPermissions.contains (eachPerm)) {
7614 continue;
7615 }
7616 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007617 if (pkg.pkg != null &&
7618 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7619 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 used = true;
7621 break;
7622 }
7623 }
7624 if (!used) {
7625 // can safely delete this permission from list
7626 sus.grantedPermissions.remove(eachPerm);
7627 sus.loadedPermissions.remove(eachPerm);
7628 }
7629 }
7630 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007631 int newGids[] = globalGids;
7632 for (String eachPerm : sus.grantedPermissions) {
7633 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007634 if (bp != null) {
7635 newGids = appendInts(newGids, bp.gids);
7636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 }
7638 sus.gids = newGids;
7639 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 private int removePackageLP(String name) {
7642 PackageSetting p = mPackages.get(name);
7643 if (p != null) {
7644 mPackages.remove(name);
7645 if (p.sharedUser != null) {
7646 p.sharedUser.packages.remove(p);
7647 if (p.sharedUser.packages.size() == 0) {
7648 mSharedUsers.remove(p.sharedUser.name);
7649 removeUserIdLP(p.sharedUser.userId);
7650 return p.sharedUser.userId;
7651 }
7652 } else {
7653 removeUserIdLP(p.userId);
7654 return p.userId;
7655 }
7656 }
7657 return -1;
7658 }
7659
7660 private boolean addUserIdLP(int uid, Object obj, Object name) {
7661 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7662 return false;
7663 }
7664
7665 if (uid >= FIRST_APPLICATION_UID) {
7666 int N = mUserIds.size();
7667 final int index = uid - FIRST_APPLICATION_UID;
7668 while (index >= N) {
7669 mUserIds.add(null);
7670 N++;
7671 }
7672 if (mUserIds.get(index) != null) {
7673 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007674 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 + " name=" + name);
7676 return false;
7677 }
7678 mUserIds.set(index, obj);
7679 } else {
7680 if (mOtherUserIds.get(uid) != null) {
7681 reportSettingsProblem(Log.ERROR,
7682 "Adding duplicate shared id: " + uid
7683 + " name=" + name);
7684 return false;
7685 }
7686 mOtherUserIds.put(uid, obj);
7687 }
7688 return true;
7689 }
7690
7691 public Object getUserIdLP(int uid) {
7692 if (uid >= FIRST_APPLICATION_UID) {
7693 int N = mUserIds.size();
7694 final int index = uid - FIRST_APPLICATION_UID;
7695 return index < N ? mUserIds.get(index) : null;
7696 } else {
7697 return mOtherUserIds.get(uid);
7698 }
7699 }
7700
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007701 private Set<String> findPackagesWithFlag(int flag) {
7702 Set<String> ret = new HashSet<String>();
7703 for (PackageSetting ps : mPackages.values()) {
7704 // Has to match atleast all the flag bits set on flag
7705 if ((ps.pkgFlags & flag) == flag) {
7706 ret.add(ps.name);
7707 }
7708 }
7709 return ret;
7710 }
7711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 private void removeUserIdLP(int uid) {
7713 if (uid >= FIRST_APPLICATION_UID) {
7714 int N = mUserIds.size();
7715 final int index = uid - FIRST_APPLICATION_UID;
7716 if (index < N) mUserIds.set(index, null);
7717 } else {
7718 mOtherUserIds.remove(uid);
7719 }
7720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 void writeLP() {
7723 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7724
7725 // Keep the old settings around until we know the new ones have
7726 // been successfully written.
7727 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007728 // Presence of backup settings file indicates that we failed
7729 // to persist settings earlier. So preserve the older
7730 // backup for future reference since the current settings
7731 // might have been corrupted.
7732 if (!mBackupSettingsFilename.exists()) {
7733 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7734 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7735 return;
7736 }
7737 } else {
7738 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 }
7741
7742 mPastSignatures.clear();
7743
7744 try {
7745 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7746
7747 //XmlSerializer serializer = XmlUtils.serializerInstance();
7748 XmlSerializer serializer = new FastXmlSerializer();
7749 serializer.setOutput(str, "utf-8");
7750 serializer.startDocument(null, true);
7751 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7752
7753 serializer.startTag(null, "packages");
7754
7755 serializer.startTag(null, "permission-trees");
7756 for (BasePermission bp : mPermissionTrees.values()) {
7757 writePermission(serializer, bp);
7758 }
7759 serializer.endTag(null, "permission-trees");
7760
7761 serializer.startTag(null, "permissions");
7762 for (BasePermission bp : mPermissions.values()) {
7763 writePermission(serializer, bp);
7764 }
7765 serializer.endTag(null, "permissions");
7766
7767 for (PackageSetting pkg : mPackages.values()) {
7768 writePackage(serializer, pkg);
7769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7772 writeDisabledSysPackage(serializer, pkg);
7773 }
7774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 serializer.startTag(null, "preferred-activities");
7776 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7777 serializer.startTag(null, "item");
7778 pa.writeToXml(serializer);
7779 serializer.endTag(null, "item");
7780 }
7781 serializer.endTag(null, "preferred-activities");
7782
7783 for (SharedUserSetting usr : mSharedUsers.values()) {
7784 serializer.startTag(null, "shared-user");
7785 serializer.attribute(null, "name", usr.name);
7786 serializer.attribute(null, "userId",
7787 Integer.toString(usr.userId));
7788 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7789 serializer.startTag(null, "perms");
7790 for (String name : usr.grantedPermissions) {
7791 serializer.startTag(null, "item");
7792 serializer.attribute(null, "name", name);
7793 serializer.endTag(null, "item");
7794 }
7795 serializer.endTag(null, "perms");
7796 serializer.endTag(null, "shared-user");
7797 }
7798
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007799 if (mPackagesToBeCleaned.size() > 0) {
7800 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7801 serializer.startTag(null, "cleaning-package");
7802 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7803 serializer.endTag(null, "cleaning-package");
7804 }
7805 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007806
7807 if (mRenamedPackages.size() > 0) {
7808 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7809 serializer.startTag(null, "renamed-package");
7810 serializer.attribute(null, "new", e.getKey());
7811 serializer.attribute(null, "old", e.getValue());
7812 serializer.endTag(null, "renamed-package");
7813 }
7814 }
7815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 serializer.endTag(null, "packages");
7817
7818 serializer.endDocument();
7819
7820 str.flush();
7821 str.close();
7822
7823 // New settings successfully written, old ones are no longer
7824 // needed.
7825 mBackupSettingsFilename.delete();
7826 FileUtils.setPermissions(mSettingsFilename.toString(),
7827 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7828 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7829 |FileUtils.S_IROTH,
7830 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007831
7832 // Write package list file now, use a JournaledFile.
7833 //
7834 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7835 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7836
7837 str = new FileOutputStream(journal.chooseForWrite());
7838 try {
7839 StringBuilder sb = new StringBuilder();
7840 for (PackageSetting pkg : mPackages.values()) {
7841 ApplicationInfo ai = pkg.pkg.applicationInfo;
7842 String dataPath = ai.dataDir;
7843 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7844
7845 // Avoid any application that has a space in its path
7846 // or that is handled by the system.
7847 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7848 continue;
7849
7850 // we store on each line the following information for now:
7851 //
7852 // pkgName - package name
7853 // userId - application-specific user id
7854 // debugFlag - 0 or 1 if the package is debuggable.
7855 // dataPath - path to package's data path
7856 //
7857 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7858 //
7859 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7860 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7861 // system/core/run-as/run-as.c
7862 //
7863 sb.setLength(0);
7864 sb.append(ai.packageName);
7865 sb.append(" ");
7866 sb.append((int)ai.uid);
7867 sb.append(isDebug ? " 1 " : " 0 ");
7868 sb.append(dataPath);
7869 sb.append("\n");
7870 str.write(sb.toString().getBytes());
7871 }
7872 str.flush();
7873 str.close();
7874 journal.commit();
7875 }
7876 catch (Exception e) {
7877 journal.rollback();
7878 }
7879
7880 FileUtils.setPermissions(mPackageListFilename.toString(),
7881 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7882 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7883 |FileUtils.S_IROTH,
7884 -1, -1);
7885
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007886 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887
7888 } catch(XmlPullParserException e) {
7889 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 } catch(java.io.IOException e) {
7891 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007893 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007894 if (mSettingsFilename.exists()) {
7895 if (!mSettingsFilename.delete()) {
7896 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7897 }
7898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 //Debug.stopMethodTracing();
7900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007901
7902 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007903 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 serializer.startTag(null, "updated-package");
7905 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007906 if (pkg.realName != null) {
7907 serializer.attribute(null, "realName", pkg.realName);
7908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 serializer.attribute(null, "codePath", pkg.codePathString);
7910 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007911 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007912 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7913 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7914 }
7915 if (pkg.sharedUser == null) {
7916 serializer.attribute(null, "userId",
7917 Integer.toString(pkg.userId));
7918 } else {
7919 serializer.attribute(null, "sharedUserId",
7920 Integer.toString(pkg.userId));
7921 }
7922 serializer.startTag(null, "perms");
7923 if (pkg.sharedUser == null) {
7924 // If this is a shared user, the permissions will
7925 // be written there. We still need to write an
7926 // empty permissions list so permissionsFixed will
7927 // be set.
7928 for (final String name : pkg.grantedPermissions) {
7929 BasePermission bp = mPermissions.get(name);
7930 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7931 // We only need to write signature or system permissions but this wont
7932 // match the semantics of grantedPermissions. So write all permissions.
7933 serializer.startTag(null, "item");
7934 serializer.attribute(null, "name", name);
7935 serializer.endTag(null, "item");
7936 }
7937 }
7938 }
7939 serializer.endTag(null, "perms");
7940 serializer.endTag(null, "updated-package");
7941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007942
7943 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007944 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 serializer.startTag(null, "package");
7946 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007947 if (pkg.realName != null) {
7948 serializer.attribute(null, "realName", pkg.realName);
7949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 serializer.attribute(null, "codePath", pkg.codePathString);
7951 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7952 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7953 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007954 serializer.attribute(null, "flags",
7955 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007957 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 if (pkg.sharedUser == null) {
7959 serializer.attribute(null, "userId",
7960 Integer.toString(pkg.userId));
7961 } else {
7962 serializer.attribute(null, "sharedUserId",
7963 Integer.toString(pkg.userId));
7964 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007965 if (pkg.uidError) {
7966 serializer.attribute(null, "uidError", "true");
7967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7969 serializer.attribute(null, "enabled",
7970 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7971 ? "true" : "false");
7972 }
7973 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7974 serializer.attribute(null, "installStatus", "false");
7975 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007976 if (pkg.installerPackageName != null) {
7977 serializer.attribute(null, "installer", pkg.installerPackageName);
7978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7980 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7981 serializer.startTag(null, "perms");
7982 if (pkg.sharedUser == null) {
7983 // If this is a shared user, the permissions will
7984 // be written there. We still need to write an
7985 // empty permissions list so permissionsFixed will
7986 // be set.
7987 for (final String name : pkg.grantedPermissions) {
7988 serializer.startTag(null, "item");
7989 serializer.attribute(null, "name", name);
7990 serializer.endTag(null, "item");
7991 }
7992 }
7993 serializer.endTag(null, "perms");
7994 }
7995 if (pkg.disabledComponents.size() > 0) {
7996 serializer.startTag(null, "disabled-components");
7997 for (final String name : pkg.disabledComponents) {
7998 serializer.startTag(null, "item");
7999 serializer.attribute(null, "name", name);
8000 serializer.endTag(null, "item");
8001 }
8002 serializer.endTag(null, "disabled-components");
8003 }
8004 if (pkg.enabledComponents.size() > 0) {
8005 serializer.startTag(null, "enabled-components");
8006 for (final String name : pkg.enabledComponents) {
8007 serializer.startTag(null, "item");
8008 serializer.attribute(null, "name", name);
8009 serializer.endTag(null, "item");
8010 }
8011 serializer.endTag(null, "enabled-components");
8012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 serializer.endTag(null, "package");
8015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 void writePermission(XmlSerializer serializer, BasePermission bp)
8018 throws XmlPullParserException, java.io.IOException {
8019 if (bp.type != BasePermission.TYPE_BUILTIN
8020 && bp.sourcePackage != null) {
8021 serializer.startTag(null, "item");
8022 serializer.attribute(null, "name", bp.name);
8023 serializer.attribute(null, "package", bp.sourcePackage);
8024 if (DEBUG_SETTINGS) Log.v(TAG,
8025 "Writing perm: name=" + bp.name + " type=" + bp.type);
8026 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8027 PermissionInfo pi = bp.perm != null ? bp.perm.info
8028 : bp.pendingInfo;
8029 if (pi != null) {
8030 serializer.attribute(null, "type", "dynamic");
8031 if (pi.icon != 0) {
8032 serializer.attribute(null, "icon",
8033 Integer.toString(pi.icon));
8034 }
8035 if (pi.nonLocalizedLabel != null) {
8036 serializer.attribute(null, "label",
8037 pi.nonLocalizedLabel.toString());
8038 }
8039 if (pi.protectionLevel !=
8040 PermissionInfo.PROTECTION_NORMAL) {
8041 serializer.attribute(null, "protection",
8042 Integer.toString(pi.protectionLevel));
8043 }
8044 }
8045 }
8046 serializer.endTag(null, "item");
8047 }
8048 }
8049
8050 String getReadMessagesLP() {
8051 return mReadMessages.toString();
8052 }
8053
Oscar Montemayora8529f62009-11-18 10:14:20 -08008054 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8056 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008057 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008058 while(its.hasNext()) {
8059 String key = its.next();
8060 PackageSetting ps = mPackages.get(key);
8061 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008062 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 }
8064 }
8065 return ret;
8066 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 boolean readLP() {
8069 FileInputStream str = null;
8070 if (mBackupSettingsFilename.exists()) {
8071 try {
8072 str = new FileInputStream(mBackupSettingsFilename);
8073 mReadMessages.append("Reading from backup settings file\n");
8074 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008075 if (mSettingsFilename.exists()) {
8076 // If both the backup and settings file exist, we
8077 // ignore the settings since it might have been
8078 // corrupted.
8079 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8080 mSettingsFilename.delete();
8081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 } catch (java.io.IOException e) {
8083 // We'll try for the normal settings file.
8084 }
8085 }
8086
8087 mPastSignatures.clear();
8088
8089 try {
8090 if (str == null) {
8091 if (!mSettingsFilename.exists()) {
8092 mReadMessages.append("No settings file found\n");
8093 Log.i(TAG, "No current settings file!");
8094 return false;
8095 }
8096 str = new FileInputStream(mSettingsFilename);
8097 }
8098 XmlPullParser parser = Xml.newPullParser();
8099 parser.setInput(str, null);
8100
8101 int type;
8102 while ((type=parser.next()) != XmlPullParser.START_TAG
8103 && type != XmlPullParser.END_DOCUMENT) {
8104 ;
8105 }
8106
8107 if (type != XmlPullParser.START_TAG) {
8108 mReadMessages.append("No start tag found in settings file\n");
8109 Log.e(TAG, "No start tag found in package manager settings");
8110 return false;
8111 }
8112
8113 int outerDepth = parser.getDepth();
8114 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8115 && (type != XmlPullParser.END_TAG
8116 || parser.getDepth() > outerDepth)) {
8117 if (type == XmlPullParser.END_TAG
8118 || type == XmlPullParser.TEXT) {
8119 continue;
8120 }
8121
8122 String tagName = parser.getName();
8123 if (tagName.equals("package")) {
8124 readPackageLP(parser);
8125 } else if (tagName.equals("permissions")) {
8126 readPermissionsLP(mPermissions, parser);
8127 } else if (tagName.equals("permission-trees")) {
8128 readPermissionsLP(mPermissionTrees, parser);
8129 } else if (tagName.equals("shared-user")) {
8130 readSharedUserLP(parser);
8131 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008132 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 } else if (tagName.equals("preferred-activities")) {
8134 readPreferredActivitiesLP(parser);
8135 } else if(tagName.equals("updated-package")) {
8136 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008137 } else if (tagName.equals("cleaning-package")) {
8138 String name = parser.getAttributeValue(null, "name");
8139 if (name != null) {
8140 mPackagesToBeCleaned.add(name);
8141 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008142 } else if (tagName.equals("renamed-package")) {
8143 String nname = parser.getAttributeValue(null, "new");
8144 String oname = parser.getAttributeValue(null, "old");
8145 if (nname != null && oname != null) {
8146 mRenamedPackages.put(nname, oname);
8147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 } else {
8149 Log.w(TAG, "Unknown element under <packages>: "
8150 + parser.getName());
8151 XmlUtils.skipCurrentTag(parser);
8152 }
8153 }
8154
8155 str.close();
8156
8157 } catch(XmlPullParserException e) {
8158 mReadMessages.append("Error reading: " + e.toString());
8159 Log.e(TAG, "Error reading package manager settings", e);
8160
8161 } catch(java.io.IOException e) {
8162 mReadMessages.append("Error reading: " + e.toString());
8163 Log.e(TAG, "Error reading package manager settings", e);
8164
8165 }
8166
8167 int N = mPendingPackages.size();
8168 for (int i=0; i<N; i++) {
8169 final PendingPackage pp = mPendingPackages.get(i);
8170 Object idObj = getUserIdLP(pp.sharedId);
8171 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008172 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008174 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 if (p == null) {
8176 Log.w(TAG, "Unable to create application package for "
8177 + pp.name);
8178 continue;
8179 }
8180 p.copyFrom(pp);
8181 } else if (idObj != null) {
8182 String msg = "Bad package setting: package " + pp.name
8183 + " has shared uid " + pp.sharedId
8184 + " that is not a shared uid\n";
8185 mReadMessages.append(msg);
8186 Log.e(TAG, msg);
8187 } else {
8188 String msg = "Bad package setting: package " + pp.name
8189 + " has shared uid " + pp.sharedId
8190 + " that is not defined\n";
8191 mReadMessages.append(msg);
8192 Log.e(TAG, msg);
8193 }
8194 }
8195 mPendingPackages.clear();
8196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 mReadMessages.append("Read completed successfully: "
8198 + mPackages.size() + " packages, "
8199 + mSharedUsers.size() + " shared uids\n");
8200
8201 return true;
8202 }
8203
8204 private int readInt(XmlPullParser parser, String ns, String name,
8205 int defValue) {
8206 String v = parser.getAttributeValue(ns, name);
8207 try {
8208 if (v == null) {
8209 return defValue;
8210 }
8211 return Integer.parseInt(v);
8212 } catch (NumberFormatException e) {
8213 reportSettingsProblem(Log.WARN,
8214 "Error in package manager settings: attribute " +
8215 name + " has bad integer value " + v + " at "
8216 + parser.getPositionDescription());
8217 }
8218 return defValue;
8219 }
8220
8221 private void readPermissionsLP(HashMap<String, BasePermission> out,
8222 XmlPullParser parser)
8223 throws IOException, XmlPullParserException {
8224 int outerDepth = parser.getDepth();
8225 int type;
8226 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8227 && (type != XmlPullParser.END_TAG
8228 || parser.getDepth() > outerDepth)) {
8229 if (type == XmlPullParser.END_TAG
8230 || type == XmlPullParser.TEXT) {
8231 continue;
8232 }
8233
8234 String tagName = parser.getName();
8235 if (tagName.equals("item")) {
8236 String name = parser.getAttributeValue(null, "name");
8237 String sourcePackage = parser.getAttributeValue(null, "package");
8238 String ptype = parser.getAttributeValue(null, "type");
8239 if (name != null && sourcePackage != null) {
8240 boolean dynamic = "dynamic".equals(ptype);
8241 BasePermission bp = new BasePermission(name, sourcePackage,
8242 dynamic
8243 ? BasePermission.TYPE_DYNAMIC
8244 : BasePermission.TYPE_NORMAL);
8245 if (dynamic) {
8246 PermissionInfo pi = new PermissionInfo();
8247 pi.packageName = sourcePackage.intern();
8248 pi.name = name.intern();
8249 pi.icon = readInt(parser, null, "icon", 0);
8250 pi.nonLocalizedLabel = parser.getAttributeValue(
8251 null, "label");
8252 pi.protectionLevel = readInt(parser, null, "protection",
8253 PermissionInfo.PROTECTION_NORMAL);
8254 bp.pendingInfo = pi;
8255 }
8256 out.put(bp.name, bp);
8257 } else {
8258 reportSettingsProblem(Log.WARN,
8259 "Error in package manager settings: permissions has"
8260 + " no name at " + parser.getPositionDescription());
8261 }
8262 } else {
8263 reportSettingsProblem(Log.WARN,
8264 "Unknown element reading permissions: "
8265 + parser.getName() + " at "
8266 + parser.getPositionDescription());
8267 }
8268 XmlUtils.skipCurrentTag(parser);
8269 }
8270 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008273 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008275 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 String codePathStr = parser.getAttributeValue(null, "codePath");
8277 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008278 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 resourcePathStr = codePathStr;
8280 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008281 String version = parser.getAttributeValue(null, "version");
8282 int versionCode = 0;
8283 if (version != null) {
8284 try {
8285 versionCode = Integer.parseInt(version);
8286 } catch (NumberFormatException e) {
8287 }
8288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 int pkgFlags = 0;
8291 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008292 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008293 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008294 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 String timeStampStr = parser.getAttributeValue(null, "ts");
8296 if (timeStampStr != null) {
8297 try {
8298 long timeStamp = Long.parseLong(timeStampStr);
8299 ps.setTimeStamp(timeStamp, timeStampStr);
8300 } catch (NumberFormatException e) {
8301 }
8302 }
8303 String idStr = parser.getAttributeValue(null, "userId");
8304 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8305 if(ps.userId <= 0) {
8306 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8307 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8308 }
8309 int outerDepth = parser.getDepth();
8310 int type;
8311 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8312 && (type != XmlPullParser.END_TAG
8313 || parser.getDepth() > outerDepth)) {
8314 if (type == XmlPullParser.END_TAG
8315 || type == XmlPullParser.TEXT) {
8316 continue;
8317 }
8318
8319 String tagName = parser.getName();
8320 if (tagName.equals("perms")) {
8321 readGrantedPermissionsLP(parser,
8322 ps.grantedPermissions);
8323 } else {
8324 reportSettingsProblem(Log.WARN,
8325 "Unknown element under <updated-package>: "
8326 + parser.getName());
8327 XmlUtils.skipCurrentTag(parser);
8328 }
8329 }
8330 mDisabledSysPackages.put(name, ps);
8331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 private void readPackageLP(XmlPullParser parser)
8334 throws XmlPullParserException, IOException {
8335 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008336 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008337 String idStr = null;
8338 String sharedIdStr = null;
8339 String codePathStr = null;
8340 String resourcePathStr = null;
8341 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008342 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008343 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 int pkgFlags = 0;
8345 String timeStampStr;
8346 long timeStamp = 0;
8347 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008348 String version = null;
8349 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 try {
8351 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008352 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008354 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8356 codePathStr = parser.getAttributeValue(null, "codePath");
8357 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008358 version = parser.getAttributeValue(null, "version");
8359 if (version != null) {
8360 try {
8361 versionCode = Integer.parseInt(version);
8362 } catch (NumberFormatException e) {
8363 }
8364 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008365 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008366
8367 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008368 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008369 try {
8370 pkgFlags = Integer.parseInt(systemStr);
8371 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 }
8373 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008374 // For backward compatibility
8375 systemStr = parser.getAttributeValue(null, "system");
8376 if (systemStr != null) {
8377 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8378 } else {
8379 // Old settings that don't specify system... just treat
8380 // them as system, good enough.
8381 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 }
8384 timeStampStr = parser.getAttributeValue(null, "ts");
8385 if (timeStampStr != null) {
8386 try {
8387 timeStamp = Long.parseLong(timeStampStr);
8388 } catch (NumberFormatException e) {
8389 }
8390 }
8391 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8392 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8393 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8394 if (resourcePathStr == null) {
8395 resourcePathStr = codePathStr;
8396 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008397 if (realName != null) {
8398 realName = realName.intern();
8399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 if (name == null) {
8401 reportSettingsProblem(Log.WARN,
8402 "Error in package manager settings: <package> has no name at "
8403 + parser.getPositionDescription());
8404 } else if (codePathStr == null) {
8405 reportSettingsProblem(Log.WARN,
8406 "Error in package manager settings: <package> has no codePath at "
8407 + parser.getPositionDescription());
8408 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008409 packageSetting = addPackageLP(name.intern(), realName,
8410 new File(codePathStr), new File(resourcePathStr),
8411 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8413 + ": userId=" + userId + " pkg=" + packageSetting);
8414 if (packageSetting == null) {
8415 reportSettingsProblem(Log.ERROR,
8416 "Failure adding uid " + userId
8417 + " while parsing settings at "
8418 + parser.getPositionDescription());
8419 } else {
8420 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8421 }
8422 } else if (sharedIdStr != null) {
8423 userId = sharedIdStr != null
8424 ? Integer.parseInt(sharedIdStr) : 0;
8425 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008426 packageSetting = new PendingPackage(name.intern(), realName,
8427 new File(codePathStr), new File(resourcePathStr),
8428 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8430 mPendingPackages.add((PendingPackage) packageSetting);
8431 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8432 + ": sharedUserId=" + userId + " pkg="
8433 + packageSetting);
8434 } else {
8435 reportSettingsProblem(Log.WARN,
8436 "Error in package manager settings: package "
8437 + name + " has bad sharedId " + sharedIdStr
8438 + " at " + parser.getPositionDescription());
8439 }
8440 } else {
8441 reportSettingsProblem(Log.WARN,
8442 "Error in package manager settings: package "
8443 + name + " has bad userId " + idStr + " at "
8444 + parser.getPositionDescription());
8445 }
8446 } catch (NumberFormatException e) {
8447 reportSettingsProblem(Log.WARN,
8448 "Error in package manager settings: package "
8449 + name + " has bad userId " + idStr + " at "
8450 + parser.getPositionDescription());
8451 }
8452 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008453 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008454 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 final String enabledStr = parser.getAttributeValue(null, "enabled");
8456 if (enabledStr != null) {
8457 if (enabledStr.equalsIgnoreCase("true")) {
8458 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8459 } else if (enabledStr.equalsIgnoreCase("false")) {
8460 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8461 } else if (enabledStr.equalsIgnoreCase("default")) {
8462 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8463 } else {
8464 reportSettingsProblem(Log.WARN,
8465 "Error in package manager settings: package "
8466 + name + " has bad enabled value: " + idStr
8467 + " at " + parser.getPositionDescription());
8468 }
8469 } else {
8470 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8471 }
8472 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8473 if (installStatusStr != null) {
8474 if (installStatusStr.equalsIgnoreCase("false")) {
8475 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8476 } else {
8477 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8478 }
8479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 int outerDepth = parser.getDepth();
8482 int type;
8483 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8484 && (type != XmlPullParser.END_TAG
8485 || parser.getDepth() > outerDepth)) {
8486 if (type == XmlPullParser.END_TAG
8487 || type == XmlPullParser.TEXT) {
8488 continue;
8489 }
8490
8491 String tagName = parser.getName();
8492 if (tagName.equals("disabled-components")) {
8493 readDisabledComponentsLP(packageSetting, parser);
8494 } else if (tagName.equals("enabled-components")) {
8495 readEnabledComponentsLP(packageSetting, parser);
8496 } else if (tagName.equals("sigs")) {
8497 packageSetting.signatures.readXml(parser, mPastSignatures);
8498 } else if (tagName.equals("perms")) {
8499 readGrantedPermissionsLP(parser,
8500 packageSetting.loadedPermissions);
8501 packageSetting.permissionsFixed = true;
8502 } else {
8503 reportSettingsProblem(Log.WARN,
8504 "Unknown element under <package>: "
8505 + parser.getName());
8506 XmlUtils.skipCurrentTag(parser);
8507 }
8508 }
8509 } else {
8510 XmlUtils.skipCurrentTag(parser);
8511 }
8512 }
8513
8514 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8515 XmlPullParser parser)
8516 throws IOException, XmlPullParserException {
8517 int outerDepth = parser.getDepth();
8518 int type;
8519 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8520 && (type != XmlPullParser.END_TAG
8521 || parser.getDepth() > outerDepth)) {
8522 if (type == XmlPullParser.END_TAG
8523 || type == XmlPullParser.TEXT) {
8524 continue;
8525 }
8526
8527 String tagName = parser.getName();
8528 if (tagName.equals("item")) {
8529 String name = parser.getAttributeValue(null, "name");
8530 if (name != null) {
8531 packageSetting.disabledComponents.add(name.intern());
8532 } else {
8533 reportSettingsProblem(Log.WARN,
8534 "Error in package manager settings: <disabled-components> has"
8535 + " no name at " + parser.getPositionDescription());
8536 }
8537 } else {
8538 reportSettingsProblem(Log.WARN,
8539 "Unknown element under <disabled-components>: "
8540 + parser.getName());
8541 }
8542 XmlUtils.skipCurrentTag(parser);
8543 }
8544 }
8545
8546 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8547 XmlPullParser parser)
8548 throws IOException, XmlPullParserException {
8549 int outerDepth = parser.getDepth();
8550 int type;
8551 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8552 && (type != XmlPullParser.END_TAG
8553 || parser.getDepth() > outerDepth)) {
8554 if (type == XmlPullParser.END_TAG
8555 || type == XmlPullParser.TEXT) {
8556 continue;
8557 }
8558
8559 String tagName = parser.getName();
8560 if (tagName.equals("item")) {
8561 String name = parser.getAttributeValue(null, "name");
8562 if (name != null) {
8563 packageSetting.enabledComponents.add(name.intern());
8564 } else {
8565 reportSettingsProblem(Log.WARN,
8566 "Error in package manager settings: <enabled-components> has"
8567 + " no name at " + parser.getPositionDescription());
8568 }
8569 } else {
8570 reportSettingsProblem(Log.WARN,
8571 "Unknown element under <enabled-components>: "
8572 + parser.getName());
8573 }
8574 XmlUtils.skipCurrentTag(parser);
8575 }
8576 }
8577
8578 private void readSharedUserLP(XmlPullParser parser)
8579 throws XmlPullParserException, IOException {
8580 String name = null;
8581 String idStr = null;
8582 int pkgFlags = 0;
8583 SharedUserSetting su = null;
8584 try {
8585 name = parser.getAttributeValue(null, "name");
8586 idStr = parser.getAttributeValue(null, "userId");
8587 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8588 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8589 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8590 }
8591 if (name == null) {
8592 reportSettingsProblem(Log.WARN,
8593 "Error in package manager settings: <shared-user> has no name at "
8594 + parser.getPositionDescription());
8595 } else if (userId == 0) {
8596 reportSettingsProblem(Log.WARN,
8597 "Error in package manager settings: shared-user "
8598 + name + " has bad userId " + idStr + " at "
8599 + parser.getPositionDescription());
8600 } else {
8601 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8602 reportSettingsProblem(Log.ERROR,
8603 "Occurred while parsing settings at "
8604 + parser.getPositionDescription());
8605 }
8606 }
8607 } catch (NumberFormatException e) {
8608 reportSettingsProblem(Log.WARN,
8609 "Error in package manager settings: package "
8610 + name + " has bad userId " + idStr + " at "
8611 + parser.getPositionDescription());
8612 };
8613
8614 if (su != null) {
8615 int outerDepth = parser.getDepth();
8616 int type;
8617 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8618 && (type != XmlPullParser.END_TAG
8619 || parser.getDepth() > outerDepth)) {
8620 if (type == XmlPullParser.END_TAG
8621 || type == XmlPullParser.TEXT) {
8622 continue;
8623 }
8624
8625 String tagName = parser.getName();
8626 if (tagName.equals("sigs")) {
8627 su.signatures.readXml(parser, mPastSignatures);
8628 } else if (tagName.equals("perms")) {
8629 readGrantedPermissionsLP(parser, su.loadedPermissions);
8630 } else {
8631 reportSettingsProblem(Log.WARN,
8632 "Unknown element under <shared-user>: "
8633 + parser.getName());
8634 XmlUtils.skipCurrentTag(parser);
8635 }
8636 }
8637
8638 } else {
8639 XmlUtils.skipCurrentTag(parser);
8640 }
8641 }
8642
8643 private void readGrantedPermissionsLP(XmlPullParser parser,
8644 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8645 int outerDepth = parser.getDepth();
8646 int type;
8647 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8648 && (type != XmlPullParser.END_TAG
8649 || parser.getDepth() > outerDepth)) {
8650 if (type == XmlPullParser.END_TAG
8651 || type == XmlPullParser.TEXT) {
8652 continue;
8653 }
8654
8655 String tagName = parser.getName();
8656 if (tagName.equals("item")) {
8657 String name = parser.getAttributeValue(null, "name");
8658 if (name != null) {
8659 outPerms.add(name.intern());
8660 } else {
8661 reportSettingsProblem(Log.WARN,
8662 "Error in package manager settings: <perms> has"
8663 + " no name at " + parser.getPositionDescription());
8664 }
8665 } else {
8666 reportSettingsProblem(Log.WARN,
8667 "Unknown element under <perms>: "
8668 + parser.getName());
8669 }
8670 XmlUtils.skipCurrentTag(parser);
8671 }
8672 }
8673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 private void readPreferredActivitiesLP(XmlPullParser parser)
8675 throws XmlPullParserException, IOException {
8676 int outerDepth = parser.getDepth();
8677 int type;
8678 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8679 && (type != XmlPullParser.END_TAG
8680 || parser.getDepth() > outerDepth)) {
8681 if (type == XmlPullParser.END_TAG
8682 || type == XmlPullParser.TEXT) {
8683 continue;
8684 }
8685
8686 String tagName = parser.getName();
8687 if (tagName.equals("item")) {
8688 PreferredActivity pa = new PreferredActivity(parser);
8689 if (pa.mParseError == null) {
8690 mPreferredActivities.addFilter(pa);
8691 } else {
8692 reportSettingsProblem(Log.WARN,
8693 "Error in package manager settings: <preferred-activity> "
8694 + pa.mParseError + " at "
8695 + parser.getPositionDescription());
8696 }
8697 } else {
8698 reportSettingsProblem(Log.WARN,
8699 "Unknown element under <preferred-activities>: "
8700 + parser.getName());
8701 XmlUtils.skipCurrentTag(parser);
8702 }
8703 }
8704 }
8705
8706 // Returns -1 if we could not find an available UserId to assign
8707 private int newUserIdLP(Object obj) {
8708 // Let's be stupidly inefficient for now...
8709 final int N = mUserIds.size();
8710 for (int i=0; i<N; i++) {
8711 if (mUserIds.get(i) == null) {
8712 mUserIds.set(i, obj);
8713 return FIRST_APPLICATION_UID + i;
8714 }
8715 }
8716
8717 // None left?
8718 if (N >= MAX_APPLICATION_UIDS) {
8719 return -1;
8720 }
8721
8722 mUserIds.add(obj);
8723 return FIRST_APPLICATION_UID + N;
8724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 public PackageSetting getDisabledSystemPkg(String name) {
8727 synchronized(mPackages) {
8728 PackageSetting ps = mDisabledSysPackages.get(name);
8729 return ps;
8730 }
8731 }
8732
8733 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8734 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8735 if (Config.LOGV) {
8736 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8737 + " componentName = " + componentInfo.name);
8738 Log.v(TAG, "enabledComponents: "
8739 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8740 Log.v(TAG, "disabledComponents: "
8741 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8742 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008743 if (packageSettings == null) {
8744 if (false) {
8745 Log.w(TAG, "WAITING FOR DEBUGGER");
8746 Debug.waitForDebugger();
8747 Log.i(TAG, "We will crash!");
8748 }
8749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8751 || ((componentInfo.enabled
8752 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8753 || (componentInfo.applicationInfo.enabled
8754 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8755 && !packageSettings.disabledComponents.contains(componentInfo.name))
8756 || packageSettings.enabledComponents.contains(componentInfo.name));
8757 }
8758 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008759
8760 // ------- apps on sdcard specific code -------
8761 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008762 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008763 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008764 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008765 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008766
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008767 private String getEncryptKey() {
8768 try {
8769 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8770 if (sdEncKey == null) {
8771 sdEncKey = SystemKeyStore.getInstance().
8772 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8773 if (sdEncKey == null) {
8774 Log.e(TAG, "Failed to create encryption keys");
8775 return null;
8776 }
8777 }
8778 return sdEncKey;
8779 } catch (NoSuchAlgorithmException nsae) {
8780 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8781 return null;
8782 }
8783 }
8784
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008785 static String getTempContainerId() {
8786 String prefix = "smdl1tmp";
8787 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008788 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008789 if (list != null) {
8790 int idx = 0;
8791 int idList[] = new int[MAX_CONTAINERS];
8792 boolean neverFound = true;
8793 for (String name : list) {
8794 // Ignore null entries
8795 if (name == null) {
8796 continue;
8797 }
8798 int sidx = name.indexOf(prefix);
8799 if (sidx == -1) {
8800 // Not a temp file. just ignore
8801 continue;
8802 }
8803 String subStr = name.substring(sidx + prefix.length());
8804 idList[idx] = -1;
8805 if (subStr != null) {
8806 try {
8807 int cid = Integer.parseInt(subStr);
8808 idList[idx++] = cid;
8809 neverFound = false;
8810 } catch (NumberFormatException e) {
8811 }
8812 }
8813 }
8814 if (!neverFound) {
8815 // Sort idList
8816 Arrays.sort(idList);
8817 for (int j = 1; j <= idList.length; j++) {
8818 if (idList[j-1] != j) {
8819 tmpIdx = j;
8820 break;
8821 }
8822 }
8823 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008824 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008825 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008826 }
8827
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008828 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008829 synchronized (mPackages) {
8830 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8831 mediaStatus+", mMediaMounted=" + mMediaMounted);
8832 if (mediaStatus == mMediaMounted) {
8833 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008834 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008835 mMediaMounted = mediaStatus;
8836 // Queue up an async operation since the package installation may take a little while.
8837 mHandler.post(new Runnable() {
8838 public void run() {
8839 mHandler.removeCallbacks(this);
8840 updateExternalMediaStatusInner(mediaStatus);
8841 }
8842 });
8843 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008844 }
8845
8846 void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008847 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008848 if (list == null || list.length == 0) {
8849 return;
8850 }
8851 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8852 int uidList[] = new int[list.length];
8853 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008854 synchronized (mPackages) {
8855 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8856 for (String cid : list) {
8857 SdInstallArgs args = new SdInstallArgs(cid);
8858 String removeEntry = null;
8859 for (String app : appList) {
8860 if (args.matchContainer(app)) {
8861 removeEntry = app;
8862 break;
8863 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008864 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008865 if (removeEntry == null) {
8866 // No matching app on device. Skip entry or may be cleanup?
8867 // Ignore default package
8868 continue;
8869 }
8870 appList.remove(removeEntry);
8871 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8872 processCids.put(args, ps.codePathString);
8873 int uid = ps.userId;
8874 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008875 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008876 }
8877 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008878 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008879 int uidArr[] = null;
8880 if (num > 0) {
8881 // Sort uid list
8882 Arrays.sort(uidList, 0, num);
8883 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008884 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008885 uidArr[0] = uidList[0];
8886 int di = 0;
8887 for (int i = 1; i < num; i++) {
8888 if (uidList[i-1] != uidList[i]) {
8889 uidArr[di++] = uidList[i];
8890 }
8891 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008892 }
8893 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008894 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008895 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008896 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008897 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008898 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008899 unloadMediaPackages(processCids, uidArr);
8900 }
8901 }
8902
8903 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8904 ArrayList<String> pkgList, int uidArr[]) {
8905 int size = pkgList.size();
8906 if (size > 0) {
8907 // Send broadcasts here
8908 Bundle extras = new Bundle();
8909 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8910 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008911 if (uidArr != null) {
8912 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8913 }
8914 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8915 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008916 sendPackageBroadcast(action, null, extras);
8917 }
8918 }
8919
8920 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8921 ArrayList<String> pkgList = new ArrayList<String>();
8922 Set<SdInstallArgs> keys = processCids.keySet();
8923 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008924 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008925 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8926 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008927 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008928 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008929 continue;
8930 }
8931 // Parse package
8932 int parseFlags = PackageParser.PARSE_CHATTY |
8933 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8934 PackageParser pp = new PackageParser(codePath);
8935 pp.setSeparateProcesses(mSeparateProcesses);
8936 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8937 codePath, mMetrics, parseFlags);
8938 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008939 Log.e(TAG, "Trying to install pkg : "
8940 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008941 continue;
8942 }
8943 setApplicationInfoPaths(pkg, codePath, codePath);
8944 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8945 synchronized (mInstallLock) {
8946 // Scan the package
8947 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8948 synchronized (mPackages) {
8949 // Grant permissions
8950 grantPermissionsLP(pkg, false);
8951 // Persist settings
8952 mSettings.writeLP();
8953 retCode = PackageManager.INSTALL_SUCCEEDED;
8954 pkgList.add(pkg.packageName);
8955 }
8956 } else {
8957 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8958 }
8959 }
8960 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008961 }
8962 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008963 if (pkgList.size() > 0) {
8964 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8965 Runtime.getRuntime().gc();
8966 // If something failed do we clean up here or next install?
8967 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008968 }
8969
8970 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008971 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008972 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008973 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008974 Set<SdInstallArgs> keys = processCids.keySet();
8975 for (SdInstallArgs args : keys) {
8976 String cid = args.cid;
8977 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008978 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008979 // Delete package internally
8980 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8981 synchronized (mInstallLock) {
8982 boolean res = deletePackageLI(pkgName, false,
8983 PackageManager.DONT_DELETE_DATA, outInfo);
8984 if (res) {
8985 pkgList.add(pkgName);
8986 } else {
8987 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008988 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008989 }
8990 }
8991 }
8992 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008993 if (pkgList.size() > 0) {
8994 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8995 Runtime.getRuntime().gc();
8996 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008997 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008998 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008999 synchronized (mInstallLock) {
9000 args.doPostDeleteLI(false);
9001 }
9002 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009003 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009004
9005 public void movePackage(final String packageName,
9006 final IPackageMoveObserver observer, final int flags) {
9007 if (packageName == null) {
9008 return;
9009 }
9010 mContext.enforceCallingOrSelfPermission(
9011 android.Manifest.permission.MOVE_PACKAGE, null);
9012 int returnCode = PackageManager.MOVE_SUCCEEDED;
9013 int currFlags = 0;
9014 int newFlags = 0;
9015 synchronized (mPackages) {
9016 PackageParser.Package pkg = mPackages.get(packageName);
9017 if (pkg == null) {
9018 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9019 }
9020 // Disable moving fwd locked apps and system packages
9021 if (pkg.applicationInfo != null &&
9022 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9023 Log.w(TAG, "Cannot move system application");
9024 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9025 } else if (pkg.applicationInfo != null &&
9026 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9027 Log.w(TAG, "Cannot move forward locked app.");
9028 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9029 } else {
9030 // Find install location first
9031 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9032 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9033 Log.w(TAG, "Ambigous flags specified for move location.");
9034 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9035 } else {
9036 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9037 PackageManager.INSTALL_EXTERNAL : 0;
9038 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
9039 PackageManager.INSTALL_EXTERNAL : 0;
9040 if (newFlags == currFlags) {
9041 Log.w(TAG, "No move required. Trying to move to same location");
9042 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9043 }
9044 }
9045 }
9046 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9047 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9048 } else {
9049 Message msg = mHandler.obtainMessage(INIT_COPY);
9050 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9051 pkg.applicationInfo.publicSourceDir);
9052 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9053 packageName);
9054 msg.obj = mp;
9055 mHandler.sendMessage(msg);
9056 }
9057 }
9058 }
9059
9060 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9061 // Queue up an async operation since the package deletion may take a little while.
9062 mHandler.post(new Runnable() {
9063 public void run() {
9064 mHandler.removeCallbacks(this);
9065 int returnCode = currentStatus;
9066 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9067 if (moveSucceeded) {
9068 int uid = -1;
9069 synchronized (mPackages) {
9070 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9071 }
9072 ArrayList<String> pkgList = new ArrayList<String>();
9073 pkgList.add(mp.packageName);
9074 int uidArr[] = new int[] { uid };
9075 // Send resources unavailable broadcast
9076 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9077
9078 // Update package code and resource paths
9079 synchronized (mPackages) {
9080 PackageParser.Package pkg = mPackages.get(mp.packageName);
9081 if (pkg != null) {
9082 String oldCodePath = pkg.mPath;
9083 String newCodePath = mp.targetArgs.getCodePath();
9084 String newResPath = mp.targetArgs.getResourcePath();
9085 pkg.mPath = newCodePath;
9086 // Move dex files around
9087 if (moveDexFiles(pkg)
9088 != PackageManager.INSTALL_SUCCEEDED) {
9089 // Moving of dex files failed. Set
9090 // error code and abort move.
9091 pkg.mPath = pkg.mScanPath;
9092 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9093 moveSucceeded = false;
9094 } else {
9095 pkg.mScanPath = newCodePath;
9096 pkg.applicationInfo.sourceDir = newCodePath;
9097 pkg.applicationInfo.publicSourceDir = newResPath;
9098 PackageSetting ps = (PackageSetting) pkg.mExtras;
9099 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9100 ps.codePathString = ps.codePath.getPath();
9101 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9102 ps.resourcePathString = ps.resourcePath.getPath();
9103 // Set the application info flag correctly.
9104 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9105 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9106 } else {
9107 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9108 }
9109 ps.setFlags(pkg.applicationInfo.flags);
9110 mAppDirs.remove(oldCodePath);
9111 mAppDirs.put(newCodePath, pkg);
9112 // Persist settings
9113 mSettings.writeLP();
9114 }
9115 }
9116 }
9117 if (moveSucceeded) {
9118 // Delete older code
9119 synchronized (mInstallLock) {
9120 mp.srcArgs.cleanUpResourcesLI();
9121 }
9122 // Send resources available broadcast
9123 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9124 Runtime.getRuntime().gc();
9125 }
9126 }
9127 if (!moveSucceeded){
9128 // Clean up failed installation
9129 if (mp.targetArgs != null) {
9130 mp.targetArgs.doPostInstall(
9131 PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
9132 }
9133 }
9134 IPackageMoveObserver observer = mp.observer;
9135 if (observer != null) {
9136 try {
9137 observer.packageMoved(mp.packageName, returnCode);
9138 } catch (RemoteException e) {
9139 Log.i(TAG, "Observer no longer exists.");
9140 }
9141 }
9142 }
9143 });
9144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145}