blob: 4a6044554336ca274095200dd2e4f54ebde88bb1 [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;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080023import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
25import org.xmlpull.v1.XmlPullParser;
26import org.xmlpull.v1.XmlPullParserException;
27import org.xmlpull.v1.XmlSerializer;
28
29import android.app.ActivityManagerNative;
30import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070035import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080036import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070037import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.pm.ActivityInfo;
39import android.content.pm.ApplicationInfo;
40import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070041import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.IPackageDataObserver;
43import android.content.pm.IPackageDeleteObserver;
44import android.content.pm.IPackageInstallObserver;
45import android.content.pm.IPackageManager;
46import android.content.pm.IPackageStatsObserver;
47import android.content.pm.InstrumentationInfo;
48import android.content.pm.PackageInfo;
49import android.content.pm.PackageManager;
50import android.content.pm.PackageStats;
51import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
52import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
53import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
54import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
55import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
56import android.content.pm.PackageParser;
57import android.content.pm.PermissionInfo;
58import android.content.pm.PermissionGroupInfo;
59import android.content.pm.ProviderInfo;
60import android.content.pm.ResolveInfo;
61import android.content.pm.ServiceInfo;
62import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.Uri;
64import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070065import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080067import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080069import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070070import android.os.Looper;
71import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Parcel;
73import android.os.RemoteException;
74import android.os.Environment;
75import android.os.FileObserver;
76import android.os.FileUtils;
77import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080078import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.ParcelFileDescriptor;
80import android.os.Process;
81import android.os.ServiceManager;
82import android.os.SystemClock;
83import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080084import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.util.*;
86import android.view.Display;
87import android.view.WindowManager;
88
89import java.io.File;
90import java.io.FileDescriptor;
91import java.io.FileInputStream;
92import java.io.FileNotFoundException;
93import java.io.FileOutputStream;
94import java.io.FileReader;
95import java.io.FilenameFilter;
96import java.io.IOException;
97import java.io.InputStream;
98import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080099import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800100import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.util.ArrayList;
102import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700103import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.util.Collections;
105import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.Enumeration;
108import java.util.HashMap;
109import java.util.HashSet;
110import java.util.Iterator;
111import java.util.List;
112import java.util.Map;
113import java.util.Set;
114import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800115import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import java.util.zip.ZipFile;
117import java.util.zip.ZipOutputStream;
118
119class PackageManagerService extends IPackageManager.Stub {
120 private static final String TAG = "PackageManager";
121 private static final boolean DEBUG_SETTINGS = false;
122 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800123 private static final boolean DEBUG_UPGRADE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
125 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
126 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400127 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private static final int FIRST_APPLICATION_UID =
129 Process.FIRST_APPLICATION_UID;
130 private static final int MAX_APPLICATION_UIDS = 1000;
131
132 private static final boolean SHOW_INFO = false;
133
134 private static final boolean GET_CERTIFICATES = true;
135
Oscar Montemayora8529f62009-11-18 10:14:20 -0800136 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private static final int REMOVE_EVENTS =
139 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
140 private static final int ADD_EVENTS =
141 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
142
143 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
144
145 static final int SCAN_MONITOR = 1<<0;
146 static final int SCAN_NO_DEX = 1<<1;
147 static final int SCAN_FORCE_DEX = 1<<2;
148 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800149 static final int SCAN_NEW_INSTALL = 1<<4;
150 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800152 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
153 "com.android.defcontainer",
154 "com.android.defcontainer.DefaultContainerService");
155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
157 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700158 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn851a5412009-05-08 12:06:44 -0700160 final int mSdkVersion = Build.VERSION.SDK_INT;
161 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
162 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 final Context mContext;
165 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700166 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 final DisplayMetrics mMetrics;
168 final int mDefParseFlags;
169 final String[] mSeparateProcesses;
170
171 // This is where all application persistent data goes.
172 final File mAppDataDir;
173
Oscar Montemayora8529f62009-11-18 10:14:20 -0800174 // If Encrypted File System feature is enabled, all application persistent data
175 // should go here instead.
176 final File mSecureAppDataDir;
177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 // This is the object monitoring the framework dir.
179 final FileObserver mFrameworkInstallObserver;
180
181 // This is the object monitoring the system app dir.
182 final FileObserver mSystemInstallObserver;
183
184 // This is the object monitoring mAppInstallDir.
185 final FileObserver mAppInstallObserver;
186
187 // This is the object monitoring mDrmAppPrivateInstallDir.
188 final FileObserver mDrmAppInstallObserver;
189
190 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
191 // LOCK HELD. Can be called with mInstallLock held.
192 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 final File mFrameworkDir;
195 final File mSystemAppDir;
196 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700197 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
199 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
200 // apps.
201 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // Lock for state used when installing and doing other long running
206 // operations. Methods that must be called with this lock held have
207 // the prefix "LI".
208 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // These are the directories in the 3rd party applications installed dir
211 // that we have currently loaded packages from. Keys are the application's
212 // installed zip file (absolute codePath), and values are Package.
213 final HashMap<String, PackageParser.Package> mAppDirs =
214 new HashMap<String, PackageParser.Package>();
215
216 // Information for the parser to write more useful error messages.
217 File mScanningPath;
218 int mLastScanError;
219
220 final int[] mOutPermissions = new int[3];
221
222 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 // Keys are String (package name), values are Package. This also serves
225 // as the lock for the global state. Methods that must be called with
226 // this lock held have the prefix "LP".
227 final HashMap<String, PackageParser.Package> mPackages =
228 new HashMap<String, PackageParser.Package>();
229
230 final Settings mSettings;
231 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
233 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
234 int[] mGlobalGids;
235
236 // These are the built-in uid -> permission mappings that were read from the
237 // etc/permissions.xml file.
238 final SparseArray<HashSet<String>> mSystemPermissions =
239 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 // These are the built-in shared libraries that were read from the
242 // etc/permissions.xml file.
243 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800244
Dianne Hackborn49237342009-08-27 20:08:01 -0700245 // Temporary for building the final shared libraries for an .apk.
246 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
Dianne Hackborn49237342009-08-27 20:08:01 -0700248 // These are the features this devices supports that were read from the
249 // etc/permissions.xml file.
250 final HashMap<String, FeatureInfo> mAvailableFeatures =
251 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 // All available activities, for your resolving pleasure.
254 final ActivityIntentResolver mActivities =
255 new ActivityIntentResolver();
256
257 // All available receivers, for your resolving pleasure.
258 final ActivityIntentResolver mReceivers =
259 new ActivityIntentResolver();
260
261 // All available services, for your resolving pleasure.
262 final ServiceIntentResolver mServices = new ServiceIntentResolver();
263
264 // Keys are String (provider class name), values are Provider.
265 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
266 new HashMap<ComponentName, PackageParser.Provider>();
267
268 // Mapping from provider base names (first directory in content URI codePath)
269 // to the provider information.
270 final HashMap<String, PackageParser.Provider> mProviders =
271 new HashMap<String, PackageParser.Provider>();
272
273 // Mapping from instrumentation class names to info about them.
274 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
275 new HashMap<ComponentName, PackageParser.Instrumentation>();
276
277 // Mapping from permission names to info about them.
278 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
279 new HashMap<String, PackageParser.PermissionGroup>();
280
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800281 // Packages whose data we have transfered into another package, thus
282 // should no longer exist.
283 final HashSet<String> mTransferedPackages = new HashSet<String>();
284
Dianne Hackborn854060af2009-07-09 18:14:31 -0700285 // Broadcast actions that are only available to the system.
286 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 boolean mSystemReady;
289 boolean mSafeMode;
290 boolean mHasSystemUidErrors;
291
292 ApplicationInfo mAndroidApplication;
293 final ActivityInfo mResolveActivity = new ActivityInfo();
294 final ResolveInfo mResolveInfo = new ResolveInfo();
295 ComponentName mResolveComponentName;
296 PackageParser.Package mPlatformPackage;
297
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700298 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800299 final HashMap<String, ArrayList<String>> mPendingBroadcasts
300 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700301 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800302 static final int MCS_BOUND = 3;
303 static final int END_COPY = 4;
304 static final int INIT_COPY = 5;
305 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800306 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700307 // Delay time in millisecs
308 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800309 private ServiceConnection mDefContainerConn = new ServiceConnection() {
310 public void onServiceConnected(ComponentName name, IBinder service) {
311 IMediaContainerService imcs =
312 IMediaContainerService.Stub.asInterface(service);
313 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
314 mHandler.sendMessage(msg);
315 }
316
317 public void onServiceDisconnected(ComponentName name) {
318 }
319 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700320
321 class PackageHandler extends Handler {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800322 final ArrayList<InstallArgs> mPendingInstalls =
323 new ArrayList<InstallArgs>();
324 // Service Connection to remote media container service to copy
325 // package uri's from external media onto secure containers
326 // or internal storage.
327 private IMediaContainerService mContainerService = null;
328
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700329 PackageHandler(Looper looper) {
330 super(looper);
331 }
332 public void handleMessage(Message msg) {
333 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800334 case INIT_COPY: {
335 InstallArgs args = (InstallArgs) msg.obj;
336 args.createCopyFile();
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800337 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800338 if (mContainerService != null) {
339 // No need to add to pending list. Use remote stub directly
340 handleStartCopy(args);
341 } else {
342 if (mContext.bindService(service, mDefContainerConn,
343 Context.BIND_AUTO_CREATE)) {
344 mPendingInstalls.add(args);
345 } else {
346 Log.e(TAG, "Failed to bind to media container service");
347 // Indicate install failure TODO add new error code
348 processPendingInstall(args,
349 PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800350 }
351 }
352 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800353 }
354 case MCS_BOUND: {
355 // Initialize mContainerService if needed.
356 if (msg.obj != null) {
357 mContainerService = (IMediaContainerService) msg.obj;
358 }
359 if (mPendingInstalls.size() > 0) {
360 InstallArgs args = mPendingInstalls.remove(0);
361 if (args != null) {
362 handleStartCopy(args);
363 }
364 }
365 break;
366 }
367 case MCS_UNBIND : {
368 if (mPendingInstalls.size() == 0) {
369 mContext.unbindService(mDefContainerConn);
370 mContainerService = null;
371 }
372 break;
373 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700374 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800375 String packages[];
376 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700377 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 int uids[];
379 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800380 if (mPendingBroadcasts == null) {
381 return;
382 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700383 size = mPendingBroadcasts.size();
384 if (size <= 0) {
385 // Nothing to be done. Just return
386 return;
387 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800388 packages = new String[size];
389 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700390 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800391 Iterator<HashMap.Entry<String, ArrayList<String>>>
392 it = mPendingBroadcasts.entrySet().iterator();
393 int i = 0;
394 while (it.hasNext() && i < size) {
395 HashMap.Entry<String, ArrayList<String>> ent = it.next();
396 packages[i] = ent.getKey();
397 components[i] = ent.getValue();
398 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700399 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800400 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800402 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700403 mPendingBroadcasts.clear();
404 }
405 // Send broadcasts
406 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800407 sendPackageChangedBroadcast(packages[i], true,
408 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700409 }
410 break;
411 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800412 case START_CLEANING_PACKAGE: {
413 String packageName = (String)msg.obj;
414 synchronized (mPackages) {
415 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
416 mSettings.mPackagesToBeCleaned.add(packageName);
417 }
418 }
419 startCleaningPackages();
420 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 }
422 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800423
424 // Utility method to initiate copying apk via media
425 // container service.
426 private void handleStartCopy(InstallArgs args) {
427 int ret = PackageManager.INSTALL_SUCCEEDED;
428 if (mContainerService == null) {
429 // Install error
430 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
431 } else {
432 ret = args.copyApk(mContainerService);
433 }
434 mHandler.sendEmptyMessage(MCS_UNBIND);
435 processPendingInstall(args, ret);
436 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700437 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800438
439 static boolean installOnSd(int flags) {
440 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
441 ((flags & PackageManager.INSTALL_ON_SDCARD) == 0)) {
442 return false;
443 }
444 return true;
445 }
446
447 static boolean isFwdLocked(int flags) {
448 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
449 return true;
450 }
451 return false;
452 }
453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 public static final IPackageManager main(Context context, boolean factoryTest) {
455 PackageManagerService m = new PackageManagerService(context, factoryTest);
456 ServiceManager.addService("package", m);
457 return m;
458 }
459
460 static String[] splitString(String str, char sep) {
461 int count = 1;
462 int i = 0;
463 while ((i=str.indexOf(sep, i)) >= 0) {
464 count++;
465 i++;
466 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 String[] res = new String[count];
469 i=0;
470 count = 0;
471 int lastI=0;
472 while ((i=str.indexOf(sep, i)) >= 0) {
473 res[count] = str.substring(lastI, i);
474 count++;
475 i++;
476 lastI = i;
477 }
478 res[count] = str.substring(lastI, str.length());
479 return res;
480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800483 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 if (mSdkVersion <= 0) {
487 Log.w(TAG, "**** ro.build.version.sdk not set!");
488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 mContext = context;
491 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700492 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 mMetrics = new DisplayMetrics();
494 mSettings = new Settings();
495 mSettings.addSharedUserLP("android.uid.system",
496 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
497 mSettings.addSharedUserLP("android.uid.phone",
498 MULTIPLE_APPLICATION_UIDS
499 ? RADIO_UID : FIRST_APPLICATION_UID,
500 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400501 mSettings.addSharedUserLP("android.uid.log",
502 MULTIPLE_APPLICATION_UIDS
503 ? LOG_UID : FIRST_APPLICATION_UID,
504 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505
506 String separateProcesses = SystemProperties.get("debug.separate_processes");
507 if (separateProcesses != null && separateProcesses.length() > 0) {
508 if ("*".equals(separateProcesses)) {
509 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
510 mSeparateProcesses = null;
511 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
512 } else {
513 mDefParseFlags = 0;
514 mSeparateProcesses = separateProcesses.split(",");
515 Log.w(TAG, "Running with debug.separate_processes: "
516 + separateProcesses);
517 }
518 } else {
519 mDefParseFlags = 0;
520 mSeparateProcesses = null;
521 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 Installer installer = new Installer();
524 // Little hacky thing to check if installd is here, to determine
525 // whether we are running on the simulator and thus need to take
526 // care of building the /data file structure ourself.
527 // (apparently the sim now has a working installer)
528 if (installer.ping() && Process.supportsProcesses()) {
529 mInstaller = installer;
530 } else {
531 mInstaller = null;
532 }
533
534 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
535 Display d = wm.getDefaultDisplay();
536 d.getMetrics(mMetrics);
537
538 synchronized (mInstallLock) {
539 synchronized (mPackages) {
540 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 File dataDir = Environment.getDataDirectory();
544 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800545 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
547
548 if (mInstaller == null) {
549 // Make sure these dirs exist, when we are running in
550 // the simulator.
551 // Make a wide-open directory for random misc stuff.
552 File miscDir = new File(dataDir, "misc");
553 miscDir.mkdirs();
554 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800555 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 mDrmAppPrivateInstallDir.mkdirs();
557 }
558
559 readPermissions();
560
561 mRestoredSettings = mSettings.readLP();
562 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800563
564 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800566
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800567 // Set flag to monitor and not change apk file paths when
568 // scanning install directories.
569 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700570 if (mNoDexOpt) {
571 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800572 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700578 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700581 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 /**
584 * Out of paranoia, ensure that everything in the boot class
585 * path has been dexed.
586 */
587 String bootClassPath = System.getProperty("java.boot.class.path");
588 if (bootClassPath != null) {
589 String[] paths = splitString(bootClassPath, ':');
590 for (int i=0; i<paths.length; i++) {
591 try {
592 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
593 libFiles.add(paths[i]);
594 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700595 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597 } catch (FileNotFoundException e) {
598 Log.w(TAG, "Boot class path not found: " + paths[i]);
599 } catch (IOException e) {
600 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
601 }
602 }
603 } else {
604 Log.w(TAG, "No BOOTCLASSPATH found!");
605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 /**
608 * Also ensure all external libraries have had dexopt run on them.
609 */
610 if (mSharedLibraries.size() > 0) {
611 Iterator<String> libs = mSharedLibraries.values().iterator();
612 while (libs.hasNext()) {
613 String lib = libs.next();
614 try {
615 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
616 libFiles.add(lib);
617 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700618 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
620 } catch (FileNotFoundException e) {
621 Log.w(TAG, "Library not found: " + lib);
622 } catch (IOException e) {
623 Log.w(TAG, "Exception reading library: " + lib, e);
624 }
625 }
626 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 // Gross hack for now: we know this file doesn't contain any
629 // code, so don't dexopt it to avoid the resulting log spew.
630 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 /**
633 * And there are a number of commands implemented in Java, which
634 * we currently need to do the dexopt on so that they can be
635 * run from a non-root shell.
636 */
637 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700638 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 for (int i=0; i<frameworkFiles.length; i++) {
640 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
641 String path = libPath.getPath();
642 // Skip the file if we alrady did it.
643 if (libFiles.contains(path)) {
644 continue;
645 }
646 // Skip the file if it is not a type we want to dexopt.
647 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
648 continue;
649 }
650 try {
651 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
652 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700653 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 }
655 } catch (FileNotFoundException e) {
656 Log.w(TAG, "Jar not found: " + path);
657 } catch (IOException e) {
658 Log.w(TAG, "Exception reading jar: " + path, e);
659 }
660 }
661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800662
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700663 if (didDexOpt) {
664 // If we had to do a dexopt of one of the previous
665 // things, then something on the system has changed.
666 // Consider this significant, and wipe away all other
667 // existing dexopt files to ensure we don't leave any
668 // dangling around.
669 String[] files = mDalvikCacheDir.list();
670 if (files != null) {
671 for (int i=0; i<files.length; i++) {
672 String fn = files[i];
673 if (fn.startsWith("data@app@")
674 || fn.startsWith("data@app-private@")) {
675 Log.i(TAG, "Pruning dalvik file: " + fn);
676 (new File(mDalvikCacheDir, fn)).delete();
677 }
678 }
679 }
680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800682
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800683 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 mFrameworkInstallObserver = new AppDirObserver(
685 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
686 mFrameworkInstallObserver.startWatching();
687 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800688 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800689
690 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
692 mSystemInstallObserver = new AppDirObserver(
693 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
694 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800695 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800696
697 if (mInstaller != null) {
698 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
699 mInstaller.moveFiles();
700 }
701
702 // Prune any system packages that no longer exist.
703 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
704 while (psit.hasNext()) {
705 PackageSetting ps = psit.next();
706 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800707 && !mPackages.containsKey(ps.name)
708 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800709 psit.remove();
710 String msg = "System package " + ps.name
711 + " no longer exists; wiping its data";
712 reportSettingsProblem(Log.WARN, msg);
713 if (mInstaller != null) {
714 // XXX how to set useEncryptedFSDir for packages that
715 // are not encrypted?
716 mInstaller.remove(ps.name, true);
717 }
718 }
719 }
720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mAppInstallDir = new File(dataDir, "app");
722 if (mInstaller == null) {
723 // Make sure these dirs exist, when we are running in
724 // the simulator.
725 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
726 }
727 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800728 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 //clean up list
730 for(int i = 0; i < deletePkgsList.size(); i++) {
731 //clean up here
732 cleanupInstallFailedPackage(deletePkgsList.get(i));
733 }
734 //delete tmp files
735 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
737 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 SystemClock.uptimeMillis());
739 mAppInstallObserver = new AppDirObserver(
740 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
741 mAppInstallObserver.startWatching();
742 scanDirLI(mAppInstallDir, 0, scanMode);
743
744 mDrmAppInstallObserver = new AppDirObserver(
745 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
746 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800747 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 SystemClock.uptimeMillis());
751 Log.i(TAG, "Time to scan packages: "
752 + ((SystemClock.uptimeMillis()-startTime)/1000f)
753 + " seconds");
754
755 updatePermissionsLP();
756
757 mSettings.writeLP();
758
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800759 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 // Now after opening every single application zip, make sure they
763 // are all flushed. Not really needed, but keeps things nice and
764 // tidy.
765 Runtime.getRuntime().gc();
766 } // synchronized (mPackages)
767 } // synchronized (mInstallLock)
768 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 @Override
771 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
772 throws RemoteException {
773 try {
774 return super.onTransact(code, data, reply, flags);
775 } catch (RuntimeException e) {
776 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
777 Log.e(TAG, "Package Manager Crash", e);
778 }
779 throw e;
780 }
781 }
782
Dianne Hackborne6620b22010-01-22 14:46:21 -0800783 void cleanupInstallFailedPackage(PackageSetting ps) {
784 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800786 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
787 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 if (retCode < 0) {
789 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800790 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792 } else {
793 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800794 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 File dataDir = new File(pkg.applicationInfo.dataDir);
796 dataDir.delete();
797 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800798 if (ps.codePath != null) {
799 if (!ps.codePath.delete()) {
800 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
801 }
802 }
803 if (ps.resourcePath != null) {
804 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
805 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
806 }
807 }
808 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 }
810
811 void readPermissions() {
812 // Read permissions from .../etc/permission directory.
813 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
814 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
815 Log.w(TAG, "No directory " + libraryDir + ", skipping");
816 return;
817 }
818 if (!libraryDir.canRead()) {
819 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
820 return;
821 }
822
823 // Iterate over the files in the directory and scan .xml files
824 for (File f : libraryDir.listFiles()) {
825 // We'll read platform.xml last
826 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
827 continue;
828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 if (!f.getPath().endsWith(".xml")) {
831 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
832 continue;
833 }
834 if (!f.canRead()) {
835 Log.w(TAG, "Permissions library file " + f + " cannot be read");
836 continue;
837 }
838
839 readPermissionsFromXml(f);
840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
843 final File permFile = new File(Environment.getRootDirectory(),
844 "etc/permissions/platform.xml");
845 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800846
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700847 StringBuilder sb = new StringBuilder(128);
848 sb.append("Libs:");
849 Iterator<String> it = mSharedLibraries.keySet().iterator();
850 while (it.hasNext()) {
851 sb.append(' ');
852 String name = it.next();
853 sb.append(name);
854 sb.append(':');
855 sb.append(mSharedLibraries.get(name));
856 }
857 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700859 sb.setLength(0);
860 sb.append("Features:");
861 it = mAvailableFeatures.keySet().iterator();
862 while (it.hasNext()) {
863 sb.append(' ');
864 sb.append(it.next());
865 }
866 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800868
869 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 FileReader permReader = null;
871 try {
872 permReader = new FileReader(permFile);
873 } catch (FileNotFoundException e) {
874 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
875 return;
876 }
877
878 try {
879 XmlPullParser parser = Xml.newPullParser();
880 parser.setInput(permReader);
881
882 XmlUtils.beginDocument(parser, "permissions");
883
884 while (true) {
885 XmlUtils.nextElement(parser);
886 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
887 break;
888 }
889
890 String name = parser.getName();
891 if ("group".equals(name)) {
892 String gidStr = parser.getAttributeValue(null, "gid");
893 if (gidStr != null) {
894 int gid = Integer.parseInt(gidStr);
895 mGlobalGids = appendInt(mGlobalGids, gid);
896 } else {
897 Log.w(TAG, "<group> without gid at "
898 + parser.getPositionDescription());
899 }
900
901 XmlUtils.skipCurrentTag(parser);
902 continue;
903 } else if ("permission".equals(name)) {
904 String perm = parser.getAttributeValue(null, "name");
905 if (perm == null) {
906 Log.w(TAG, "<permission> without name at "
907 + parser.getPositionDescription());
908 XmlUtils.skipCurrentTag(parser);
909 continue;
910 }
911 perm = perm.intern();
912 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 } else if ("assign-permission".equals(name)) {
915 String perm = parser.getAttributeValue(null, "name");
916 if (perm == null) {
917 Log.w(TAG, "<assign-permission> without name at "
918 + parser.getPositionDescription());
919 XmlUtils.skipCurrentTag(parser);
920 continue;
921 }
922 String uidStr = parser.getAttributeValue(null, "uid");
923 if (uidStr == null) {
924 Log.w(TAG, "<assign-permission> without uid at "
925 + parser.getPositionDescription());
926 XmlUtils.skipCurrentTag(parser);
927 continue;
928 }
929 int uid = Process.getUidForName(uidStr);
930 if (uid < 0) {
931 Log.w(TAG, "<assign-permission> with unknown uid \""
932 + uidStr + "\" at "
933 + parser.getPositionDescription());
934 XmlUtils.skipCurrentTag(parser);
935 continue;
936 }
937 perm = perm.intern();
938 HashSet<String> perms = mSystemPermissions.get(uid);
939 if (perms == null) {
940 perms = new HashSet<String>();
941 mSystemPermissions.put(uid, perms);
942 }
943 perms.add(perm);
944 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 } else if ("library".equals(name)) {
947 String lname = parser.getAttributeValue(null, "name");
948 String lfile = parser.getAttributeValue(null, "file");
949 if (lname == null) {
950 Log.w(TAG, "<library> without name at "
951 + parser.getPositionDescription());
952 } else if (lfile == null) {
953 Log.w(TAG, "<library> without file at "
954 + parser.getPositionDescription());
955 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700956 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700957 mSharedLibraries.put(lname, lfile);
958 }
959 XmlUtils.skipCurrentTag(parser);
960 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961
Dianne Hackborn49237342009-08-27 20:08:01 -0700962 } else if ("feature".equals(name)) {
963 String fname = parser.getAttributeValue(null, "name");
964 if (fname == null) {
965 Log.w(TAG, "<feature> without name at "
966 + parser.getPositionDescription());
967 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700968 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700969 FeatureInfo fi = new FeatureInfo();
970 fi.name = fname;
971 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973 XmlUtils.skipCurrentTag(parser);
974 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 } else {
977 XmlUtils.skipCurrentTag(parser);
978 continue;
979 }
980
981 }
982 } catch (XmlPullParserException e) {
983 Log.w(TAG, "Got execption parsing permissions.", e);
984 } catch (IOException e) {
985 Log.w(TAG, "Got execption parsing permissions.", e);
986 }
987 }
988
989 void readPermission(XmlPullParser parser, String name)
990 throws IOException, XmlPullParserException {
991
992 name = name.intern();
993
994 BasePermission bp = mSettings.mPermissions.get(name);
995 if (bp == null) {
996 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
997 mSettings.mPermissions.put(name, bp);
998 }
999 int outerDepth = parser.getDepth();
1000 int type;
1001 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1002 && (type != XmlPullParser.END_TAG
1003 || parser.getDepth() > outerDepth)) {
1004 if (type == XmlPullParser.END_TAG
1005 || type == XmlPullParser.TEXT) {
1006 continue;
1007 }
1008
1009 String tagName = parser.getName();
1010 if ("group".equals(tagName)) {
1011 String gidStr = parser.getAttributeValue(null, "gid");
1012 if (gidStr != null) {
1013 int gid = Process.getGidForName(gidStr);
1014 bp.gids = appendInt(bp.gids, gid);
1015 } else {
1016 Log.w(TAG, "<group> without gid at "
1017 + parser.getPositionDescription());
1018 }
1019 }
1020 XmlUtils.skipCurrentTag(parser);
1021 }
1022 }
1023
1024 static int[] appendInt(int[] cur, int val) {
1025 if (cur == null) {
1026 return new int[] { val };
1027 }
1028 final int N = cur.length;
1029 for (int i=0; i<N; i++) {
1030 if (cur[i] == val) {
1031 return cur;
1032 }
1033 }
1034 int[] ret = new int[N+1];
1035 System.arraycopy(cur, 0, ret, 0, N);
1036 ret[N] = val;
1037 return ret;
1038 }
1039
1040 static int[] appendInts(int[] cur, int[] add) {
1041 if (add == null) return cur;
1042 if (cur == null) return add;
1043 final int N = add.length;
1044 for (int i=0; i<N; i++) {
1045 cur = appendInt(cur, add[i]);
1046 }
1047 return cur;
1048 }
1049
1050 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001051 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1052 // The package has been uninstalled but has retained data and resources.
1053 return PackageParser.generatePackageInfo(p, null, flags);
1054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 final PackageSetting ps = (PackageSetting)p.mExtras;
1056 if (ps == null) {
1057 return null;
1058 }
1059 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1060 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1061 }
1062
1063 public PackageInfo getPackageInfo(String packageName, int flags) {
1064 synchronized (mPackages) {
1065 PackageParser.Package p = mPackages.get(packageName);
1066 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001067 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 + ": " + p);
1069 if (p != null) {
1070 return generatePackageInfo(p, flags);
1071 }
1072 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1073 return generatePackageInfoFromSettingsLP(packageName, flags);
1074 }
1075 }
1076 return null;
1077 }
1078
1079 public int getPackageUid(String packageName) {
1080 synchronized (mPackages) {
1081 PackageParser.Package p = mPackages.get(packageName);
1082 if(p != null) {
1083 return p.applicationInfo.uid;
1084 }
1085 PackageSetting ps = mSettings.mPackages.get(packageName);
1086 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1087 return -1;
1088 }
1089 p = ps.pkg;
1090 return p != null ? p.applicationInfo.uid : -1;
1091 }
1092 }
1093
1094 public int[] getPackageGids(String packageName) {
1095 synchronized (mPackages) {
1096 PackageParser.Package p = mPackages.get(packageName);
1097 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001098 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 + ": " + p);
1100 if (p != null) {
1101 final PackageSetting ps = (PackageSetting)p.mExtras;
1102 final SharedUserSetting suid = ps.sharedUser;
1103 return suid != null ? suid.gids : ps.gids;
1104 }
1105 }
1106 // stupid thing to indicate an error.
1107 return new int[0];
1108 }
1109
1110 public PermissionInfo getPermissionInfo(String name, int flags) {
1111 synchronized (mPackages) {
1112 final BasePermission p = mSettings.mPermissions.get(name);
1113 if (p != null && p.perm != null) {
1114 return PackageParser.generatePermissionInfo(p.perm, flags);
1115 }
1116 return null;
1117 }
1118 }
1119
1120 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1121 synchronized (mPackages) {
1122 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1123 for (BasePermission p : mSettings.mPermissions.values()) {
1124 if (group == null) {
1125 if (p.perm.info.group == null) {
1126 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1127 }
1128 } else {
1129 if (group.equals(p.perm.info.group)) {
1130 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1131 }
1132 }
1133 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 if (out.size() > 0) {
1136 return out;
1137 }
1138 return mPermissionGroups.containsKey(group) ? out : null;
1139 }
1140 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1143 synchronized (mPackages) {
1144 return PackageParser.generatePermissionGroupInfo(
1145 mPermissionGroups.get(name), flags);
1146 }
1147 }
1148
1149 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1150 synchronized (mPackages) {
1151 final int N = mPermissionGroups.size();
1152 ArrayList<PermissionGroupInfo> out
1153 = new ArrayList<PermissionGroupInfo>(N);
1154 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1155 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1156 }
1157 return out;
1158 }
1159 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1162 PackageSetting ps = mSettings.mPackages.get(packageName);
1163 if(ps != null) {
1164 if(ps.pkg == null) {
1165 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1166 if(pInfo != null) {
1167 return pInfo.applicationInfo;
1168 }
1169 return null;
1170 }
1171 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1172 }
1173 return null;
1174 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1177 PackageSetting ps = mSettings.mPackages.get(packageName);
1178 if(ps != null) {
1179 if(ps.pkg == null) {
1180 ps.pkg = new PackageParser.Package(packageName);
1181 ps.pkg.applicationInfo.packageName = packageName;
1182 }
1183 return generatePackageInfo(ps.pkg, flags);
1184 }
1185 return null;
1186 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1189 synchronized (mPackages) {
1190 PackageParser.Package p = mPackages.get(packageName);
1191 if (Config.LOGV) Log.v(
1192 TAG, "getApplicationInfo " + packageName
1193 + ": " + p);
1194 if (p != null) {
1195 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001196 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
1198 if ("android".equals(packageName)||"system".equals(packageName)) {
1199 return mAndroidApplication;
1200 }
1201 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1202 return generateApplicationInfoFromSettingsLP(packageName, flags);
1203 }
1204 }
1205 return null;
1206 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
1208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1210 mContext.enforceCallingOrSelfPermission(
1211 android.Manifest.permission.CLEAR_APP_CACHE, null);
1212 // Queue up an async operation since clearing cache may take a little while.
1213 mHandler.post(new Runnable() {
1214 public void run() {
1215 mHandler.removeCallbacks(this);
1216 int retCode = -1;
1217 if (mInstaller != null) {
1218 retCode = mInstaller.freeCache(freeStorageSize);
1219 if (retCode < 0) {
1220 Log.w(TAG, "Couldn't clear application caches");
1221 }
1222 } //end if mInstaller
1223 if (observer != null) {
1224 try {
1225 observer.onRemoveCompleted(null, (retCode >= 0));
1226 } catch (RemoteException e) {
1227 Log.w(TAG, "RemoveException when invoking call back");
1228 }
1229 }
1230 }
1231 });
1232 }
1233
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001234 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001235 mContext.enforceCallingOrSelfPermission(
1236 android.Manifest.permission.CLEAR_APP_CACHE, null);
1237 // Queue up an async operation since clearing cache may take a little while.
1238 mHandler.post(new Runnable() {
1239 public void run() {
1240 mHandler.removeCallbacks(this);
1241 int retCode = -1;
1242 if (mInstaller != null) {
1243 retCode = mInstaller.freeCache(freeStorageSize);
1244 if (retCode < 0) {
1245 Log.w(TAG, "Couldn't clear application caches");
1246 }
1247 }
1248 if(pi != null) {
1249 try {
1250 // Callback via pending intent
1251 int code = (retCode >= 0) ? 1 : 0;
1252 pi.sendIntent(null, code, null,
1253 null, null);
1254 } catch (SendIntentException e1) {
1255 Log.i(TAG, "Failed to send pending intent");
1256 }
1257 }
1258 }
1259 });
1260 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1263 synchronized (mPackages) {
1264 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001265
1266 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001268 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
1270 if (mResolveComponentName.equals(component)) {
1271 return mResolveActivity;
1272 }
1273 }
1274 return null;
1275 }
1276
1277 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1278 synchronized (mPackages) {
1279 PackageParser.Activity a = mReceivers.mActivities.get(component);
1280 if (Config.LOGV) Log.v(
1281 TAG, "getReceiverInfo " + component + ": " + a);
1282 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1283 return PackageParser.generateActivityInfo(a, flags);
1284 }
1285 }
1286 return null;
1287 }
1288
1289 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1290 synchronized (mPackages) {
1291 PackageParser.Service s = mServices.mServices.get(component);
1292 if (Config.LOGV) Log.v(
1293 TAG, "getServiceInfo " + component + ": " + s);
1294 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1295 return PackageParser.generateServiceInfo(s, flags);
1296 }
1297 }
1298 return null;
1299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 public String[] getSystemSharedLibraryNames() {
1302 Set<String> libSet;
1303 synchronized (mPackages) {
1304 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001305 int size = libSet.size();
1306 if (size > 0) {
1307 String[] libs = new String[size];
1308 libSet.toArray(libs);
1309 return libs;
1310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001312 return null;
1313 }
1314
1315 public FeatureInfo[] getSystemAvailableFeatures() {
1316 Collection<FeatureInfo> featSet;
1317 synchronized (mPackages) {
1318 featSet = mAvailableFeatures.values();
1319 int size = featSet.size();
1320 if (size > 0) {
1321 FeatureInfo[] features = new FeatureInfo[size+1];
1322 featSet.toArray(features);
1323 FeatureInfo fi = new FeatureInfo();
1324 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1325 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1326 features[size] = fi;
1327 return features;
1328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330 return null;
1331 }
1332
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001333 public boolean hasSystemFeature(String name) {
1334 synchronized (mPackages) {
1335 return mAvailableFeatures.containsKey(name);
1336 }
1337 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 public int checkPermission(String permName, String pkgName) {
1340 synchronized (mPackages) {
1341 PackageParser.Package p = mPackages.get(pkgName);
1342 if (p != null && p.mExtras != null) {
1343 PackageSetting ps = (PackageSetting)p.mExtras;
1344 if (ps.sharedUser != null) {
1345 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1346 return PackageManager.PERMISSION_GRANTED;
1347 }
1348 } else if (ps.grantedPermissions.contains(permName)) {
1349 return PackageManager.PERMISSION_GRANTED;
1350 }
1351 }
1352 }
1353 return PackageManager.PERMISSION_DENIED;
1354 }
1355
1356 public int checkUidPermission(String permName, int uid) {
1357 synchronized (mPackages) {
1358 Object obj = mSettings.getUserIdLP(uid);
1359 if (obj != null) {
1360 if (obj instanceof SharedUserSetting) {
1361 SharedUserSetting sus = (SharedUserSetting)obj;
1362 if (sus.grantedPermissions.contains(permName)) {
1363 return PackageManager.PERMISSION_GRANTED;
1364 }
1365 } else if (obj instanceof PackageSetting) {
1366 PackageSetting ps = (PackageSetting)obj;
1367 if (ps.grantedPermissions.contains(permName)) {
1368 return PackageManager.PERMISSION_GRANTED;
1369 }
1370 }
1371 } else {
1372 HashSet<String> perms = mSystemPermissions.get(uid);
1373 if (perms != null && perms.contains(permName)) {
1374 return PackageManager.PERMISSION_GRANTED;
1375 }
1376 }
1377 }
1378 return PackageManager.PERMISSION_DENIED;
1379 }
1380
1381 private BasePermission findPermissionTreeLP(String permName) {
1382 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1383 if (permName.startsWith(bp.name) &&
1384 permName.length() > bp.name.length() &&
1385 permName.charAt(bp.name.length()) == '.') {
1386 return bp;
1387 }
1388 }
1389 return null;
1390 }
1391
1392 private BasePermission checkPermissionTreeLP(String permName) {
1393 if (permName != null) {
1394 BasePermission bp = findPermissionTreeLP(permName);
1395 if (bp != null) {
1396 if (bp.uid == Binder.getCallingUid()) {
1397 return bp;
1398 }
1399 throw new SecurityException("Calling uid "
1400 + Binder.getCallingUid()
1401 + " is not allowed to add to permission tree "
1402 + bp.name + " owned by uid " + bp.uid);
1403 }
1404 }
1405 throw new SecurityException("No permission tree found for " + permName);
1406 }
1407
1408 public boolean addPermission(PermissionInfo info) {
1409 synchronized (mPackages) {
1410 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1411 throw new SecurityException("Label must be specified in permission");
1412 }
1413 BasePermission tree = checkPermissionTreeLP(info.name);
1414 BasePermission bp = mSettings.mPermissions.get(info.name);
1415 boolean added = bp == null;
1416 if (added) {
1417 bp = new BasePermission(info.name, tree.sourcePackage,
1418 BasePermission.TYPE_DYNAMIC);
1419 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1420 throw new SecurityException(
1421 "Not allowed to modify non-dynamic permission "
1422 + info.name);
1423 }
1424 bp.perm = new PackageParser.Permission(tree.perm.owner,
1425 new PermissionInfo(info));
1426 bp.perm.info.packageName = tree.perm.info.packageName;
1427 bp.uid = tree.uid;
1428 if (added) {
1429 mSettings.mPermissions.put(info.name, bp);
1430 }
1431 mSettings.writeLP();
1432 return added;
1433 }
1434 }
1435
1436 public void removePermission(String name) {
1437 synchronized (mPackages) {
1438 checkPermissionTreeLP(name);
1439 BasePermission bp = mSettings.mPermissions.get(name);
1440 if (bp != null) {
1441 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1442 throw new SecurityException(
1443 "Not allowed to modify non-dynamic permission "
1444 + name);
1445 }
1446 mSettings.mPermissions.remove(name);
1447 mSettings.writeLP();
1448 }
1449 }
1450 }
1451
Dianne Hackborn854060af2009-07-09 18:14:31 -07001452 public boolean isProtectedBroadcast(String actionName) {
1453 synchronized (mPackages) {
1454 return mProtectedBroadcasts.contains(actionName);
1455 }
1456 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 public int checkSignatures(String pkg1, String pkg2) {
1459 synchronized (mPackages) {
1460 PackageParser.Package p1 = mPackages.get(pkg1);
1461 PackageParser.Package p2 = mPackages.get(pkg2);
1462 if (p1 == null || p1.mExtras == null
1463 || p2 == null || p2.mExtras == null) {
1464 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1465 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001466 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 }
1469
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001470 public int checkUidSignatures(int uid1, int uid2) {
1471 synchronized (mPackages) {
1472 Signature[] s1;
1473 Signature[] s2;
1474 Object obj = mSettings.getUserIdLP(uid1);
1475 if (obj != null) {
1476 if (obj instanceof SharedUserSetting) {
1477 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1478 } else if (obj instanceof PackageSetting) {
1479 s1 = ((PackageSetting)obj).signatures.mSignatures;
1480 } else {
1481 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1482 }
1483 } else {
1484 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1485 }
1486 obj = mSettings.getUserIdLP(uid2);
1487 if (obj != null) {
1488 if (obj instanceof SharedUserSetting) {
1489 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1490 } else if (obj instanceof PackageSetting) {
1491 s2 = ((PackageSetting)obj).signatures.mSignatures;
1492 } else {
1493 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1494 }
1495 } else {
1496 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1497 }
1498 return checkSignaturesLP(s1, s2);
1499 }
1500 }
1501
1502 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1503 if (s1 == null) {
1504 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1506 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1507 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001508 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1510 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001511 final int N1 = s1.length;
1512 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 for (int i=0; i<N1; i++) {
1514 boolean match = false;
1515 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001516 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 match = true;
1518 break;
1519 }
1520 }
1521 if (!match) {
1522 return PackageManager.SIGNATURE_NO_MATCH;
1523 }
1524 }
1525 return PackageManager.SIGNATURE_MATCH;
1526 }
1527
1528 public String[] getPackagesForUid(int uid) {
1529 synchronized (mPackages) {
1530 Object obj = mSettings.getUserIdLP(uid);
1531 if (obj instanceof SharedUserSetting) {
1532 SharedUserSetting sus = (SharedUserSetting)obj;
1533 final int N = sus.packages.size();
1534 String[] res = new String[N];
1535 Iterator<PackageSetting> it = sus.packages.iterator();
1536 int i=0;
1537 while (it.hasNext()) {
1538 res[i++] = it.next().name;
1539 }
1540 return res;
1541 } else if (obj instanceof PackageSetting) {
1542 PackageSetting ps = (PackageSetting)obj;
1543 return new String[] { ps.name };
1544 }
1545 }
1546 return null;
1547 }
1548
1549 public String getNameForUid(int uid) {
1550 synchronized (mPackages) {
1551 Object obj = mSettings.getUserIdLP(uid);
1552 if (obj instanceof SharedUserSetting) {
1553 SharedUserSetting sus = (SharedUserSetting)obj;
1554 return sus.name + ":" + sus.userId;
1555 } else if (obj instanceof PackageSetting) {
1556 PackageSetting ps = (PackageSetting)obj;
1557 return ps.name;
1558 }
1559 }
1560 return null;
1561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 public int getUidForSharedUser(String sharedUserName) {
1564 if(sharedUserName == null) {
1565 return -1;
1566 }
1567 synchronized (mPackages) {
1568 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1569 if(suid == null) {
1570 return -1;
1571 }
1572 return suid.userId;
1573 }
1574 }
1575
1576 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1577 int flags) {
1578 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001579 return chooseBestActivity(intent, resolvedType, flags, query);
1580 }
1581
Mihai Predaeae850c2009-05-13 10:13:48 +02001582 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1583 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (query != null) {
1585 final int N = query.size();
1586 if (N == 1) {
1587 return query.get(0);
1588 } else if (N > 1) {
1589 // If there is more than one activity with the same priority,
1590 // then let the user decide between them.
1591 ResolveInfo r0 = query.get(0);
1592 ResolveInfo r1 = query.get(1);
1593 if (false) {
1594 System.out.println(r0.activityInfo.name +
1595 "=" + r0.priority + " vs " +
1596 r1.activityInfo.name +
1597 "=" + r1.priority);
1598 }
1599 // If the first activity has a higher priority, or a different
1600 // default, then it is always desireable to pick it.
1601 if (r0.priority != r1.priority
1602 || r0.preferredOrder != r1.preferredOrder
1603 || r0.isDefault != r1.isDefault) {
1604 return query.get(0);
1605 }
1606 // If we have saved a preference for a preferred activity for
1607 // this Intent, use that.
1608 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1609 flags, query, r0.priority);
1610 if (ri != null) {
1611 return ri;
1612 }
1613 return mResolveInfo;
1614 }
1615 }
1616 return null;
1617 }
1618
1619 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1620 int flags, List<ResolveInfo> query, int priority) {
1621 synchronized (mPackages) {
1622 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1623 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001624 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1626 if (prefs != null && prefs.size() > 0) {
1627 // First figure out how good the original match set is.
1628 // We will only allow preferred activities that came
1629 // from the same match quality.
1630 int match = 0;
1631 final int N = query.size();
1632 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1633 for (int j=0; j<N; j++) {
1634 ResolveInfo ri = query.get(j);
1635 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1636 + ": 0x" + Integer.toHexString(match));
1637 if (ri.match > match) match = ri.match;
1638 }
1639 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1640 + Integer.toHexString(match));
1641 match &= IntentFilter.MATCH_CATEGORY_MASK;
1642 final int M = prefs.size();
1643 for (int i=0; i<M; i++) {
1644 PreferredActivity pa = prefs.get(i);
1645 if (pa.mMatch != match) {
1646 continue;
1647 }
1648 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1649 if (DEBUG_PREFERRED) {
1650 Log.v(TAG, "Got preferred activity:");
1651 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1652 }
1653 if (ai != null) {
1654 for (int j=0; j<N; j++) {
1655 ResolveInfo ri = query.get(j);
1656 if (!ri.activityInfo.applicationInfo.packageName
1657 .equals(ai.applicationInfo.packageName)) {
1658 continue;
1659 }
1660 if (!ri.activityInfo.name.equals(ai.name)) {
1661 continue;
1662 }
1663
1664 // Okay we found a previously set preferred app.
1665 // If the result set is different from when this
1666 // was created, we need to clear it and re-ask the
1667 // user their preference.
1668 if (!pa.sameSet(query, priority)) {
1669 Log.i(TAG, "Result set changed, dropping preferred activity for "
1670 + intent + " type " + resolvedType);
1671 mSettings.mPreferredActivities.removeFilter(pa);
1672 return null;
1673 }
1674
1675 // Yay!
1676 return ri;
1677 }
1678 }
1679 }
1680 }
1681 }
1682 return null;
1683 }
1684
1685 public List<ResolveInfo> queryIntentActivities(Intent intent,
1686 String resolvedType, int flags) {
1687 ComponentName comp = intent.getComponent();
1688 if (comp != null) {
1689 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1690 ActivityInfo ai = getActivityInfo(comp, flags);
1691 if (ai != null) {
1692 ResolveInfo ri = new ResolveInfo();
1693 ri.activityInfo = ai;
1694 list.add(ri);
1695 }
1696 return list;
1697 }
1698
1699 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001700 String pkgName = intent.getPackage();
1701 if (pkgName == null) {
1702 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1703 resolvedType, flags);
1704 }
1705 PackageParser.Package pkg = mPackages.get(pkgName);
1706 if (pkg != null) {
1707 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1708 resolvedType, flags, pkg.activities);
1709 }
1710 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
1712 }
1713
1714 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1715 Intent[] specifics, String[] specificTypes, Intent intent,
1716 String resolvedType, int flags) {
1717 final String resultsAction = intent.getAction();
1718
1719 List<ResolveInfo> results = queryIntentActivities(
1720 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1721 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1722
1723 int specificsPos = 0;
1724 int N;
1725
1726 // todo: note that the algorithm used here is O(N^2). This
1727 // isn't a problem in our current environment, but if we start running
1728 // into situations where we have more than 5 or 10 matches then this
1729 // should probably be changed to something smarter...
1730
1731 // First we go through and resolve each of the specific items
1732 // that were supplied, taking care of removing any corresponding
1733 // duplicate items in the generic resolve list.
1734 if (specifics != null) {
1735 for (int i=0; i<specifics.length; i++) {
1736 final Intent sintent = specifics[i];
1737 if (sintent == null) {
1738 continue;
1739 }
1740
1741 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1742 String action = sintent.getAction();
1743 if (resultsAction != null && resultsAction.equals(action)) {
1744 // If this action was explicitly requested, then don't
1745 // remove things that have it.
1746 action = null;
1747 }
1748 ComponentName comp = sintent.getComponent();
1749 ResolveInfo ri = null;
1750 ActivityInfo ai = null;
1751 if (comp == null) {
1752 ri = resolveIntent(
1753 sintent,
1754 specificTypes != null ? specificTypes[i] : null,
1755 flags);
1756 if (ri == null) {
1757 continue;
1758 }
1759 if (ri == mResolveInfo) {
1760 // ACK! Must do something better with this.
1761 }
1762 ai = ri.activityInfo;
1763 comp = new ComponentName(ai.applicationInfo.packageName,
1764 ai.name);
1765 } else {
1766 ai = getActivityInfo(comp, flags);
1767 if (ai == null) {
1768 continue;
1769 }
1770 }
1771
1772 // Look for any generic query activities that are duplicates
1773 // of this specific one, and remove them from the results.
1774 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1775 N = results.size();
1776 int j;
1777 for (j=specificsPos; j<N; j++) {
1778 ResolveInfo sri = results.get(j);
1779 if ((sri.activityInfo.name.equals(comp.getClassName())
1780 && sri.activityInfo.applicationInfo.packageName.equals(
1781 comp.getPackageName()))
1782 || (action != null && sri.filter.matchAction(action))) {
1783 results.remove(j);
1784 if (Config.LOGV) Log.v(
1785 TAG, "Removing duplicate item from " + j
1786 + " due to specific " + specificsPos);
1787 if (ri == null) {
1788 ri = sri;
1789 }
1790 j--;
1791 N--;
1792 }
1793 }
1794
1795 // Add this specific item to its proper place.
1796 if (ri == null) {
1797 ri = new ResolveInfo();
1798 ri.activityInfo = ai;
1799 }
1800 results.add(specificsPos, ri);
1801 ri.specificIndex = i;
1802 specificsPos++;
1803 }
1804 }
1805
1806 // Now we go through the remaining generic results and remove any
1807 // duplicate actions that are found here.
1808 N = results.size();
1809 for (int i=specificsPos; i<N-1; i++) {
1810 final ResolveInfo rii = results.get(i);
1811 if (rii.filter == null) {
1812 continue;
1813 }
1814
1815 // Iterate over all of the actions of this result's intent
1816 // filter... typically this should be just one.
1817 final Iterator<String> it = rii.filter.actionsIterator();
1818 if (it == null) {
1819 continue;
1820 }
1821 while (it.hasNext()) {
1822 final String action = it.next();
1823 if (resultsAction != null && resultsAction.equals(action)) {
1824 // If this action was explicitly requested, then don't
1825 // remove things that have it.
1826 continue;
1827 }
1828 for (int j=i+1; j<N; j++) {
1829 final ResolveInfo rij = results.get(j);
1830 if (rij.filter != null && rij.filter.hasAction(action)) {
1831 results.remove(j);
1832 if (Config.LOGV) Log.v(
1833 TAG, "Removing duplicate item from " + j
1834 + " due to action " + action + " at " + i);
1835 j--;
1836 N--;
1837 }
1838 }
1839 }
1840
1841 // If the caller didn't request filter information, drop it now
1842 // so we don't have to marshall/unmarshall it.
1843 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1844 rii.filter = null;
1845 }
1846 }
1847
1848 // Filter out the caller activity if so requested.
1849 if (caller != null) {
1850 N = results.size();
1851 for (int i=0; i<N; i++) {
1852 ActivityInfo ainfo = results.get(i).activityInfo;
1853 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1854 && caller.getClassName().equals(ainfo.name)) {
1855 results.remove(i);
1856 break;
1857 }
1858 }
1859 }
1860
1861 // If the caller didn't request filter information,
1862 // drop them now so we don't have to
1863 // marshall/unmarshall it.
1864 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1865 N = results.size();
1866 for (int i=0; i<N; i++) {
1867 results.get(i).filter = null;
1868 }
1869 }
1870
1871 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1872 return results;
1873 }
1874
1875 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1876 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001877 ComponentName comp = intent.getComponent();
1878 if (comp != null) {
1879 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1880 ActivityInfo ai = getReceiverInfo(comp, flags);
1881 if (ai != null) {
1882 ResolveInfo ri = new ResolveInfo();
1883 ri.activityInfo = ai;
1884 list.add(ri);
1885 }
1886 return list;
1887 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001890 String pkgName = intent.getPackage();
1891 if (pkgName == null) {
1892 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1893 resolvedType, flags);
1894 }
1895 PackageParser.Package pkg = mPackages.get(pkgName);
1896 if (pkg != null) {
1897 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1898 resolvedType, flags, pkg.receivers);
1899 }
1900 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902 }
1903
1904 public ResolveInfo resolveService(Intent intent, String resolvedType,
1905 int flags) {
1906 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1907 flags);
1908 if (query != null) {
1909 if (query.size() >= 1) {
1910 // If there is more than one service with the same priority,
1911 // just arbitrarily pick the first one.
1912 return query.get(0);
1913 }
1914 }
1915 return null;
1916 }
1917
1918 public List<ResolveInfo> queryIntentServices(Intent intent,
1919 String resolvedType, int flags) {
1920 ComponentName comp = intent.getComponent();
1921 if (comp != null) {
1922 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1923 ServiceInfo si = getServiceInfo(comp, flags);
1924 if (si != null) {
1925 ResolveInfo ri = new ResolveInfo();
1926 ri.serviceInfo = si;
1927 list.add(ri);
1928 }
1929 return list;
1930 }
1931
1932 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001933 String pkgName = intent.getPackage();
1934 if (pkgName == null) {
1935 return (List<ResolveInfo>)mServices.queryIntent(intent,
1936 resolvedType, flags);
1937 }
1938 PackageParser.Package pkg = mPackages.get(pkgName);
1939 if (pkg != null) {
1940 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1941 resolvedType, flags, pkg.services);
1942 }
1943 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 public List<PackageInfo> getInstalledPackages(int flags) {
1948 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1949
1950 synchronized (mPackages) {
1951 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1952 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1953 while (i.hasNext()) {
1954 final PackageSetting ps = i.next();
1955 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1956 if(psPkg != null) {
1957 finalList.add(psPkg);
1958 }
1959 }
1960 }
1961 else {
1962 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1963 while (i.hasNext()) {
1964 final PackageParser.Package p = i.next();
1965 if (p.applicationInfo != null) {
1966 PackageInfo pi = generatePackageInfo(p, flags);
1967 if(pi != null) {
1968 finalList.add(pi);
1969 }
1970 }
1971 }
1972 }
1973 }
1974 return finalList;
1975 }
1976
1977 public List<ApplicationInfo> getInstalledApplications(int flags) {
1978 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1979 synchronized(mPackages) {
1980 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1981 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1982 while (i.hasNext()) {
1983 final PackageSetting ps = i.next();
1984 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1985 if(ai != null) {
1986 finalList.add(ai);
1987 }
1988 }
1989 }
1990 else {
1991 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1992 while (i.hasNext()) {
1993 final PackageParser.Package p = i.next();
1994 if (p.applicationInfo != null) {
1995 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1996 if(ai != null) {
1997 finalList.add(ai);
1998 }
1999 }
2000 }
2001 }
2002 }
2003 return finalList;
2004 }
2005
2006 public List<ApplicationInfo> getPersistentApplications(int flags) {
2007 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2008
2009 synchronized (mPackages) {
2010 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2011 while (i.hasNext()) {
2012 PackageParser.Package p = i.next();
2013 if (p.applicationInfo != null
2014 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2015 && (!mSafeMode || (p.applicationInfo.flags
2016 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2017 finalList.add(p.applicationInfo);
2018 }
2019 }
2020 }
2021
2022 return finalList;
2023 }
2024
2025 public ProviderInfo resolveContentProvider(String name, int flags) {
2026 synchronized (mPackages) {
2027 final PackageParser.Provider provider = mProviders.get(name);
2028 return provider != null
2029 && mSettings.isEnabledLP(provider.info, flags)
2030 && (!mSafeMode || (provider.info.applicationInfo.flags
2031 &ApplicationInfo.FLAG_SYSTEM) != 0)
2032 ? PackageParser.generateProviderInfo(provider, flags)
2033 : null;
2034 }
2035 }
2036
Fred Quintana718d8a22009-04-29 17:53:20 -07002037 /**
2038 * @deprecated
2039 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 public void querySyncProviders(List outNames, List outInfo) {
2041 synchronized (mPackages) {
2042 Iterator<Map.Entry<String, PackageParser.Provider>> i
2043 = mProviders.entrySet().iterator();
2044
2045 while (i.hasNext()) {
2046 Map.Entry<String, PackageParser.Provider> entry = i.next();
2047 PackageParser.Provider p = entry.getValue();
2048
2049 if (p.syncable
2050 && (!mSafeMode || (p.info.applicationInfo.flags
2051 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2052 outNames.add(entry.getKey());
2053 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2054 }
2055 }
2056 }
2057 }
2058
2059 public List<ProviderInfo> queryContentProviders(String processName,
2060 int uid, int flags) {
2061 ArrayList<ProviderInfo> finalList = null;
2062
2063 synchronized (mPackages) {
2064 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2065 while (i.hasNext()) {
2066 PackageParser.Provider p = i.next();
2067 if (p.info.authority != null
2068 && (processName == null ||
2069 (p.info.processName.equals(processName)
2070 && p.info.applicationInfo.uid == uid))
2071 && mSettings.isEnabledLP(p.info, flags)
2072 && (!mSafeMode || (p.info.applicationInfo.flags
2073 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2074 if (finalList == null) {
2075 finalList = new ArrayList<ProviderInfo>(3);
2076 }
2077 finalList.add(PackageParser.generateProviderInfo(p,
2078 flags));
2079 }
2080 }
2081 }
2082
2083 if (finalList != null) {
2084 Collections.sort(finalList, mProviderInitOrderSorter);
2085 }
2086
2087 return finalList;
2088 }
2089
2090 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2091 int flags) {
2092 synchronized (mPackages) {
2093 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2094 return PackageParser.generateInstrumentationInfo(i, flags);
2095 }
2096 }
2097
2098 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2099 int flags) {
2100 ArrayList<InstrumentationInfo> finalList =
2101 new ArrayList<InstrumentationInfo>();
2102
2103 synchronized (mPackages) {
2104 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2105 while (i.hasNext()) {
2106 PackageParser.Instrumentation p = i.next();
2107 if (targetPackage == null
2108 || targetPackage.equals(p.info.targetPackage)) {
2109 finalList.add(PackageParser.generateInstrumentationInfo(p,
2110 flags));
2111 }
2112 }
2113 }
2114
2115 return finalList;
2116 }
2117
2118 private void scanDirLI(File dir, int flags, int scanMode) {
2119 Log.d(TAG, "Scanning app dir " + dir);
2120
2121 String[] files = dir.list();
2122
2123 int i;
2124 for (i=0; i<files.length; i++) {
2125 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002126 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002128 // Don't mess around with apps in system partition.
2129 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0) {
2130 // Delete the apk
2131 Log.w(TAG, "Cleaning up failed install of " + file);
2132 file.delete();
2133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
2135 }
2136
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002137 private static File getSettingsProblemFile() {
2138 File dataDir = Environment.getDataDirectory();
2139 File systemDir = new File(dataDir, "system");
2140 File fname = new File(systemDir, "uiderrors.txt");
2141 return fname;
2142 }
2143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 private static void reportSettingsProblem(int priority, String msg) {
2145 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002146 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 FileOutputStream out = new FileOutputStream(fname, true);
2148 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002149 SimpleDateFormat formatter = new SimpleDateFormat();
2150 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2151 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 pw.close();
2153 FileUtils.setPermissions(
2154 fname.toString(),
2155 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2156 -1, -1);
2157 } catch (java.io.IOException e) {
2158 }
2159 Log.println(priority, TAG, msg);
2160 }
2161
2162 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2163 PackageParser.Package pkg, File srcFile, int parseFlags) {
2164 if (GET_CERTIFICATES) {
2165 if (ps == null || !ps.codePath.equals(srcFile)
2166 || ps.getTimeStamp() != srcFile.lastModified()) {
2167 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2168 if (!pp.collectCertificates(pkg, parseFlags)) {
2169 mLastScanError = pp.getParseError();
2170 return false;
2171 }
2172 }
2173 }
2174 return true;
2175 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 /*
2178 * Scan a package and return the newly parsed package.
2179 * Returns null in case of errors and the error code is stored in mLastScanError
2180 */
2181 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002182 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002184 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002186 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002189 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 if (pkg == null) {
2191 mLastScanError = pp.getParseError();
2192 return null;
2193 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002194 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 PackageSetting updatedPkg;
2196 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002197 // Look to see if we already know about this package.
2198 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
2199 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2200 // This package has been renamed to its original name. Let's
2201 // use that.
2202 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2203 }
2204 // If there was no original package, see one for the real package name.
2205 if (ps == null) {
2206 ps = mSettings.peekPackageLP(pkg.packageName);
2207 }
2208 // Check to see if this package could be hiding/updating a system
2209 // package. Must look for it either under the original or real
2210 // package name depending on our state.
2211 updatedPkg = mSettings.mDisabledSysPackages.get(
2212 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002214 // First check if this is a system package that may involve an update
2215 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2216 if (!ps.codePath.equals(scanFile)) {
2217 // The path has changed from what was last scanned... check the
2218 // version of the new path against what we have stored to determine
2219 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002220 if (pkg.mVersionCode < ps.versionCode) {
2221 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002222 // Ignore entry. Skip it.
2223 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2224 + "ignored: updated version " + ps.versionCode
2225 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002226 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2227 return null;
2228 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002229 // The current app on the system partion is better than
2230 // what we have updated to on the data partition; switch
2231 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002232 // At this point, its safely assumed that package installation for
2233 // apps in system partition will go through. If not there won't be a working
2234 // version of the app
2235 synchronized (mPackages) {
2236 // Just remove the loaded entries from package lists.
2237 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002238 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002239 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2240 + "reverting from " + ps.codePathString
2241 + ": new version " + pkg.mVersionCode
2242 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002243 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2244 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002245 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 }
2248 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002249 if (updatedPkg != null) {
2250 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2251 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2252 }
2253 // Verify certificates against what was last scanned
2254 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2255 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2256 return null;
2257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 // The apk is forward locked (not public) if its code and resources
2259 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002260 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002262 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002263 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002264
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002265 String codePath = null;
2266 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002267 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2268 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002269 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002270 } else {
2271 // Should not happen at all. Just log an error.
2272 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2273 }
2274 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002275 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002276 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002277 codePath = pkg.mScanPath;
2278 // Set application objects path explicitly.
2279 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002281 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 }
2283
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002284 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2285 String destCodePath, String destResPath) {
2286 pkg.mPath = pkg.mScanPath = destCodePath;
2287 pkg.applicationInfo.sourceDir = destCodePath;
2288 pkg.applicationInfo.publicSourceDir = destResPath;
2289 }
2290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 private static String fixProcessName(String defProcessName,
2292 String processName, int uid) {
2293 if (processName == null) {
2294 return defProcessName;
2295 }
2296 return processName;
2297 }
2298
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002299 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2301 if (pkg.mSignatures != null) {
2302 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2303 updateSignature)) {
2304 Log.e(TAG, "Package " + pkg.packageName
2305 + " signatures do not match the previously installed version; ignoring!");
2306 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2307 return false;
2308 }
2309
2310 if (pkgSetting.sharedUser != null) {
2311 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2312 pkg.mSignatures, updateSignature)) {
2313 Log.e(TAG, "Package " + pkg.packageName
2314 + " has no signatures that match those in shared user "
2315 + pkgSetting.sharedUser.name + "; ignoring!");
2316 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2317 return false;
2318 }
2319 }
2320 } else {
2321 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2322 }
2323 return true;
2324 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002325
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002326 public boolean performDexOpt(String packageName) {
2327 if (!mNoDexOpt) {
2328 return false;
2329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002330
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002331 PackageParser.Package p;
2332 synchronized (mPackages) {
2333 p = mPackages.get(packageName);
2334 if (p == null || p.mDidDexOpt) {
2335 return false;
2336 }
2337 }
2338 synchronized (mInstallLock) {
2339 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2340 }
2341 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002342
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002343 static final int DEX_OPT_SKIPPED = 0;
2344 static final int DEX_OPT_PERFORMED = 1;
2345 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002346
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002347 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2348 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002349 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002350 String path = pkg.mScanPath;
2351 int ret = 0;
2352 try {
2353 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002354 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002355 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002356 pkg.mDidDexOpt = true;
2357 performed = true;
2358 }
2359 } catch (FileNotFoundException e) {
2360 Log.w(TAG, "Apk not found for dexopt: " + path);
2361 ret = -1;
2362 } catch (IOException e) {
2363 Log.w(TAG, "Exception reading apk: " + path, e);
2364 ret = -1;
2365 }
2366 if (ret < 0) {
2367 //error from installer
2368 return DEX_OPT_FAILED;
2369 }
2370 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002371
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002372 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2373 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002374
2375 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2376 return Environment.isEncryptedFilesystemEnabled() &&
2377 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2378 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002379
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002380 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2381 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2382 Log.w(TAG, "Unable to update from " + oldPkg.name
2383 + " to " + newPkg.packageName
2384 + ": old package not in system partition");
2385 return false;
2386 } else if (mPackages.get(oldPkg.name) != null) {
2387 Log.w(TAG, "Unable to update from " + oldPkg.name
2388 + " to " + newPkg.packageName
2389 + ": old package still exists");
2390 return false;
2391 }
2392 return true;
2393 }
2394
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002395 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2396 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002397 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002398 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2399 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002400 // Bail out. The resource and code paths haven't been set.
2401 Log.w(TAG, " Code and resource paths haven't been set correctly");
2402 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2403 return null;
2404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 mScanningPath = scanFile;
2406 if (pkg == null) {
2407 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2408 return null;
2409 }
2410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2412 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2413 }
2414
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002415 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 synchronized (mPackages) {
2417 if (mAndroidApplication != null) {
2418 Log.w(TAG, "*************************************************");
2419 Log.w(TAG, "Core android package being redefined. Skipping.");
2420 Log.w(TAG, " file=" + mScanningPath);
2421 Log.w(TAG, "*************************************************");
2422 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2423 return null;
2424 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 // Set up information for our fall-back user intent resolution
2427 // activity.
2428 mPlatformPackage = pkg;
2429 pkg.mVersionCode = mSdkVersion;
2430 mAndroidApplication = pkg.applicationInfo;
2431 mResolveActivity.applicationInfo = mAndroidApplication;
2432 mResolveActivity.name = ResolverActivity.class.getName();
2433 mResolveActivity.packageName = mAndroidApplication.packageName;
2434 mResolveActivity.processName = mAndroidApplication.processName;
2435 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2436 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2437 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2438 mResolveActivity.exported = true;
2439 mResolveActivity.enabled = true;
2440 mResolveInfo.activityInfo = mResolveActivity;
2441 mResolveInfo.priority = 0;
2442 mResolveInfo.preferredOrder = 0;
2443 mResolveInfo.match = 0;
2444 mResolveComponentName = new ComponentName(
2445 mAndroidApplication.packageName, mResolveActivity.name);
2446 }
2447 }
2448
2449 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002450 TAG, "Scanning package " + pkg.packageName);
2451 if (mPackages.containsKey(pkg.packageName)
2452 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002454 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 + " already installed. Skipping duplicate.");
2456 Log.w(TAG, "*************************************************");
2457 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2458 return null;
2459 }
2460
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002461 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002462 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2463 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 SharedUserSetting suid = null;
2466 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002469
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002470 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2471 // Only system apps can use these features.
2472 pkg.mOriginalPackage = null;
2473 pkg.mRealPackage = null;
2474 pkg.mAdoptPermissions = null;
2475 }
2476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 synchronized (mPackages) {
2478 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002479 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2480 if (mTmpSharedLibraries == null ||
2481 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2482 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2483 }
2484 int num = 0;
2485 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2486 for (int i=0; i<N; i++) {
2487 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 if (file == null) {
2489 Log.e(TAG, "Package " + pkg.packageName
2490 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002491 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2493 return null;
2494 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002495 mTmpSharedLibraries[num] = file;
2496 num++;
2497 }
2498 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2499 for (int i=0; i<N; i++) {
2500 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2501 if (file == null) {
2502 Log.w(TAG, "Package " + pkg.packageName
2503 + " desires unavailable shared library "
2504 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2505 } else {
2506 mTmpSharedLibraries[num] = file;
2507 num++;
2508 }
2509 }
2510 if (num > 0) {
2511 pkg.usesLibraryFiles = new String[num];
2512 System.arraycopy(mTmpSharedLibraries, 0,
2513 pkg.usesLibraryFiles, 0, num);
2514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002515
Dianne Hackborn49237342009-08-27 20:08:01 -07002516 if (pkg.reqFeatures != null) {
2517 N = pkg.reqFeatures.size();
2518 for (int i=0; i<N; i++) {
2519 FeatureInfo fi = pkg.reqFeatures.get(i);
2520 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2521 // Don't care.
2522 continue;
2523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002524
Dianne Hackborn49237342009-08-27 20:08:01 -07002525 if (fi.name != null) {
2526 if (mAvailableFeatures.get(fi.name) == null) {
2527 Log.e(TAG, "Package " + pkg.packageName
2528 + " requires unavailable feature "
2529 + fi.name + "; failing!");
2530 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2531 return null;
2532 }
2533 }
2534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 }
2536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 if (pkg.mSharedUserId != null) {
2539 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2540 pkg.applicationInfo.flags, true);
2541 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002542 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 + " for shared user failed");
2544 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2545 return null;
2546 }
2547 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2548 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2549 + suid.userId + "): packages=" + suid.packages);
2550 }
2551 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002552
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002553 if (false) {
2554 if (pkg.mOriginalPackage != null) {
2555 Log.w(TAG, "WAITING FOR DEBUGGER");
2556 Debug.waitForDebugger();
2557 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2558 + pkg.mOriginalPackage);
2559 }
2560 }
2561
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002562 // Check if we are renaming from an original package name.
2563 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002564 String realName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002565 if (pkg.mOriginalPackage != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002566 // This package may need to be renamed to a previously
2567 // installed name. Let's check on that...
2568 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
2569 if (pkg.mOriginalPackage.equals(renamed)) {
2570 // This package had originally been installed as the
2571 // original name, and we have already taken care of
2572 // transitioning to the new one. Just update the new
2573 // one to continue using the old name.
2574 realName = pkg.mRealPackage;
2575 if (!pkg.packageName.equals(renamed)) {
2576 // Callers into this function may have already taken
2577 // care of renaming the package; only do it here if
2578 // it is not already done.
2579 pkg.setPackageName(renamed);
2580 }
2581
2582 } else if ((origPackage
2583 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2584 // We do have the package already installed under its
2585 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002586 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002588 origPackage = null;
2589 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002591 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2592 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2593 + " to " + pkg.packageName + ": old uid "
2594 + origPackage.sharedUser.name
2595 + " differs from " + pkg.mSharedUserId);
2596 origPackage = null;
2597 }
2598 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2600 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002601 }
2602 }
2603 }
2604
2605 if (mTransferedPackages.contains(pkg.packageName)) {
2606 Log.w(TAG, "Package " + pkg.packageName
2607 + " was transferred to another, but its .apk remains");
2608 }
2609
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002610 // Just create the setting, don't add it yet. For already existing packages
2611 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002612 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 destResourceFile, pkg.applicationInfo.flags, true, false);
2614 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002615 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2617 return null;
2618 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619
2620 if (pkgSetting.origPackage != null) {
2621 // If we are first transitioning from an original package,
2622 // fix up the new package's name now. We need to do this after
2623 // looking up the package under its new name, so getPackageLP
2624 // can take care of fiddling things correctly.
2625 pkg.setPackageName(origPackage.name);
2626
2627 // File a report about this.
2628 String msg = "New package " + pkgSetting.realName
2629 + " renamed to replace old package " + pkgSetting.name;
2630 reportSettingsProblem(Log.WARN, msg);
2631
2632 // Make a note of it.
2633 mTransferedPackages.add(origPackage.name);
2634
2635 // No longer need to retain this.
2636 pkgSetting.origPackage = null;
2637 }
2638
2639 if (realName != null) {
2640 // Make a note of it.
2641 mTransferedPackages.add(pkg.packageName);
2642 }
2643
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002644 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 pkg.applicationInfo.uid = pkgSetting.userId;
2649 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002650
2651 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2653 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2654 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2655 return null;
2656 }
2657 // The signature has changed, but this package is in the system
2658 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002659 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 // However... if this package is part of a shared user, but it
2661 // doesn't match the signature of the shared user, let's fail.
2662 // What this means is that you can't change the signatures
2663 // associated with an overall shared user, which doesn't seem all
2664 // that unreasonable.
2665 if (pkgSetting.sharedUser != null) {
2666 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2667 pkg.mSignatures, false)) {
2668 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2669 return null;
2670 }
2671 }
2672 removeExisting = true;
2673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002674
The Android Open Source Project10592532009-03-18 17:39:46 -07002675 // Verify that this new package doesn't have any content providers
2676 // that conflict with existing packages. Only do this if the
2677 // package isn't already installed, since we don't want to break
2678 // things that are installed.
2679 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2680 int N = pkg.providers.size();
2681 int i;
2682 for (i=0; i<N; i++) {
2683 PackageParser.Provider p = pkg.providers.get(i);
2684 String names[] = p.info.authority.split(";");
2685 for (int j = 0; j < names.length; j++) {
2686 if (mProviders.containsKey(names[j])) {
2687 PackageParser.Provider other = mProviders.get(names[j]);
2688 Log.w(TAG, "Can't install because provider name " + names[j] +
2689 " (in package " + pkg.applicationInfo.packageName +
2690 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002691 + ((other != null && other.getComponentName() != null)
2692 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002693 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2694 return null;
2695 }
2696 }
2697 }
2698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
2700
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002701 final String pkgName = pkg.packageName;
2702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002704 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002706 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 if (ret != 0) {
2708 String msg = "System package " + pkg.packageName
2709 + " could not have data directory erased after signature change.";
2710 reportSettingsProblem(Log.WARN, msg);
2711 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2712 return null;
2713 }
2714 }
2715 Log.w(TAG, "System package " + pkg.packageName
2716 + " signature changed: existing data removed.");
2717 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002720 if (pkg.mAdoptPermissions != null) {
2721 // This package wants to adopt ownership of permissions from
2722 // another package.
2723 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2724 String origName = pkg.mAdoptPermissions.get(i);
2725 PackageSetting orig = mSettings.peekPackageLP(origName);
2726 if (orig != null) {
2727 if (verifyPackageUpdate(orig, pkg)) {
2728 Log.i(TAG, "Adopting permissions from "
2729 + origName + " to " + pkg.packageName);
2730 mSettings.transferPermissions(origName, pkg.packageName);
2731 }
2732 }
2733 }
2734 }
2735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 long scanFileTime = scanFile.lastModified();
2737 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2738 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2739 pkg.applicationInfo.processName = fixProcessName(
2740 pkg.applicationInfo.packageName,
2741 pkg.applicationInfo.processName,
2742 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743
2744 File dataPath;
2745 if (mPlatformPackage == pkg) {
2746 // The system package is special.
2747 dataPath = new File (Environment.getDataDirectory(), "system");
2748 pkg.applicationInfo.dataDir = dataPath.getPath();
2749 } else {
2750 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002751 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2752 if (useEncryptedFSDir) {
2753 dataPath = new File(mSecureAppDataDir, pkgName);
2754 } else {
2755 dataPath = new File(mAppDataDir, pkgName);
2756 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002757
2758 boolean uidError = false;
2759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 if (dataPath.exists()) {
2761 mOutPermissions[1] = 0;
2762 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2763 if (mOutPermissions[1] == pkg.applicationInfo.uid
2764 || !Process.supportsProcesses()) {
2765 pkg.applicationInfo.dataDir = dataPath.getPath();
2766 } else {
2767 boolean recovered = false;
2768 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2769 // If this is a system app, we can at least delete its
2770 // current data so the application will still work.
2771 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002772 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002773 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 // Old data gone!
2775 String msg = "System package " + pkg.packageName
2776 + " has changed from uid: "
2777 + mOutPermissions[1] + " to "
2778 + pkg.applicationInfo.uid + "; old data erased";
2779 reportSettingsProblem(Log.WARN, msg);
2780 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002783 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 pkg.applicationInfo.uid);
2785 if (ret == -1) {
2786 // Ack should not happen!
2787 msg = "System package " + pkg.packageName
2788 + " could not have data directory re-created after delete.";
2789 reportSettingsProblem(Log.WARN, msg);
2790 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2791 return null;
2792 }
2793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 if (!recovered) {
2796 mHasSystemUidErrors = true;
2797 }
2798 }
2799 if (!recovered) {
2800 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2801 + pkg.applicationInfo.uid + "/fs_"
2802 + mOutPermissions[1];
2803 String msg = "Package " + pkg.packageName
2804 + " has mismatched uid: "
2805 + mOutPermissions[1] + " on disk, "
2806 + pkg.applicationInfo.uid + " in settings";
2807 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002808 mSettings.mReadMessages.append(msg);
2809 mSettings.mReadMessages.append('\n');
2810 uidError = true;
2811 if (!pkgSetting.uidError) {
2812 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 }
2815 }
2816 }
2817 pkg.applicationInfo.dataDir = dataPath.getPath();
2818 } else {
2819 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2820 Log.v(TAG, "Want this data dir: " + dataPath);
2821 //invoke installer to do the actual installation
2822 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002823 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 pkg.applicationInfo.uid);
2825 if(ret < 0) {
2826 // Error from installer
2827 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2828 return null;
2829 }
2830 } else {
2831 dataPath.mkdirs();
2832 if (dataPath.exists()) {
2833 FileUtils.setPermissions(
2834 dataPath.toString(),
2835 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2836 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2837 }
2838 }
2839 if (dataPath.exists()) {
2840 pkg.applicationInfo.dataDir = dataPath.getPath();
2841 } else {
2842 Log.w(TAG, "Unable to create data directory: " + dataPath);
2843 pkg.applicationInfo.dataDir = null;
2844 }
2845 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002846
2847 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 }
2849
2850 // Perform shared library installation and dex validation and
2851 // optimization, if this is not a system app.
2852 if (mInstaller != null) {
2853 String path = scanFile.getPath();
2854 if (scanFileNewer) {
2855 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002856 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2857 if (err != PackageManager.INSTALL_SUCCEEDED) {
2858 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 return null;
2860 }
2861 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002862 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002863
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002864 if ((scanMode&SCAN_NO_DEX) == 0) {
2865 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2867 return null;
2868 }
2869 }
2870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 if (mFactoryTest && pkg.requestedPermissions.contains(
2873 android.Manifest.permission.FACTORY_TEST)) {
2874 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2875 }
2876
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002877 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 mAppDirs.put(pkg.mPath, pkg);
2880 }
2881
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002882 // Request the ActivityManager to kill the process(only for existing packages)
2883 // so that we do not end up in a confused state while the user is still using the older
2884 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002885 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002886 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002887 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002888 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002892 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002894 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002895 // Make sure we don't accidentally delete its data.
2896 mSettings.mPackagesToBeCleaned.remove(pkgName);
2897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 int N = pkg.providers.size();
2899 StringBuilder r = null;
2900 int i;
2901 for (i=0; i<N; i++) {
2902 PackageParser.Provider p = pkg.providers.get(i);
2903 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2904 p.info.processName, pkg.applicationInfo.uid);
2905 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2906 p.info.name), p);
2907 p.syncable = p.info.isSyncable;
2908 String names[] = p.info.authority.split(";");
2909 p.info.authority = null;
2910 for (int j = 0; j < names.length; j++) {
2911 if (j == 1 && p.syncable) {
2912 // We only want the first authority for a provider to possibly be
2913 // syncable, so if we already added this provider using a different
2914 // authority clear the syncable flag. We copy the provider before
2915 // changing it because the mProviders object contains a reference
2916 // to a provider that we don't want to change.
2917 // Only do this for the second authority since the resulting provider
2918 // object can be the same for all future authorities for this provider.
2919 p = new PackageParser.Provider(p);
2920 p.syncable = false;
2921 }
2922 if (!mProviders.containsKey(names[j])) {
2923 mProviders.put(names[j], p);
2924 if (p.info.authority == null) {
2925 p.info.authority = names[j];
2926 } else {
2927 p.info.authority = p.info.authority + ";" + names[j];
2928 }
2929 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2930 Log.d(TAG, "Registered content provider: " + names[j] +
2931 ", className = " + p.info.name +
2932 ", isSyncable = " + p.info.isSyncable);
2933 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002934 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 Log.w(TAG, "Skipping provider name " + names[j] +
2936 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002937 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002938 + ((other != null && other.getComponentName() != null)
2939 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941 }
2942 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2943 if (r == null) {
2944 r = new StringBuilder(256);
2945 } else {
2946 r.append(' ');
2947 }
2948 r.append(p.info.name);
2949 }
2950 }
2951 if (r != null) {
2952 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 N = pkg.services.size();
2956 r = null;
2957 for (i=0; i<N; i++) {
2958 PackageParser.Service s = pkg.services.get(i);
2959 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2960 s.info.processName, pkg.applicationInfo.uid);
2961 mServices.addService(s);
2962 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2963 if (r == null) {
2964 r = new StringBuilder(256);
2965 } else {
2966 r.append(' ');
2967 }
2968 r.append(s.info.name);
2969 }
2970 }
2971 if (r != null) {
2972 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2973 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 N = pkg.receivers.size();
2976 r = null;
2977 for (i=0; i<N; i++) {
2978 PackageParser.Activity a = pkg.receivers.get(i);
2979 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2980 a.info.processName, pkg.applicationInfo.uid);
2981 mReceivers.addActivity(a, "receiver");
2982 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2983 if (r == null) {
2984 r = new StringBuilder(256);
2985 } else {
2986 r.append(' ');
2987 }
2988 r.append(a.info.name);
2989 }
2990 }
2991 if (r != null) {
2992 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 N = pkg.activities.size();
2996 r = null;
2997 for (i=0; i<N; i++) {
2998 PackageParser.Activity a = pkg.activities.get(i);
2999 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3000 a.info.processName, pkg.applicationInfo.uid);
3001 mActivities.addActivity(a, "activity");
3002 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3003 if (r == null) {
3004 r = new StringBuilder(256);
3005 } else {
3006 r.append(' ');
3007 }
3008 r.append(a.info.name);
3009 }
3010 }
3011 if (r != null) {
3012 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3013 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 N = pkg.permissionGroups.size();
3016 r = null;
3017 for (i=0; i<N; i++) {
3018 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3019 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3020 if (cur == null) {
3021 mPermissionGroups.put(pg.info.name, pg);
3022 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3023 if (r == null) {
3024 r = new StringBuilder(256);
3025 } else {
3026 r.append(' ');
3027 }
3028 r.append(pg.info.name);
3029 }
3030 } else {
3031 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3032 + pg.info.packageName + " ignored: original from "
3033 + cur.info.packageName);
3034 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3035 if (r == null) {
3036 r = new StringBuilder(256);
3037 } else {
3038 r.append(' ');
3039 }
3040 r.append("DUP:");
3041 r.append(pg.info.name);
3042 }
3043 }
3044 }
3045 if (r != null) {
3046 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3047 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 N = pkg.permissions.size();
3050 r = null;
3051 for (i=0; i<N; i++) {
3052 PackageParser.Permission p = pkg.permissions.get(i);
3053 HashMap<String, BasePermission> permissionMap =
3054 p.tree ? mSettings.mPermissionTrees
3055 : mSettings.mPermissions;
3056 p.group = mPermissionGroups.get(p.info.group);
3057 if (p.info.group == null || p.group != null) {
3058 BasePermission bp = permissionMap.get(p.info.name);
3059 if (bp == null) {
3060 bp = new BasePermission(p.info.name, p.info.packageName,
3061 BasePermission.TYPE_NORMAL);
3062 permissionMap.put(p.info.name, bp);
3063 }
3064 if (bp.perm == null) {
3065 if (bp.sourcePackage == null
3066 || bp.sourcePackage.equals(p.info.packageName)) {
3067 BasePermission tree = findPermissionTreeLP(p.info.name);
3068 if (tree == null
3069 || tree.sourcePackage.equals(p.info.packageName)) {
3070 bp.perm = p;
3071 bp.uid = pkg.applicationInfo.uid;
3072 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3073 if (r == null) {
3074 r = new StringBuilder(256);
3075 } else {
3076 r.append(' ');
3077 }
3078 r.append(p.info.name);
3079 }
3080 } else {
3081 Log.w(TAG, "Permission " + p.info.name + " from package "
3082 + p.info.packageName + " ignored: base tree "
3083 + tree.name + " is from package "
3084 + tree.sourcePackage);
3085 }
3086 } else {
3087 Log.w(TAG, "Permission " + p.info.name + " from package "
3088 + p.info.packageName + " ignored: original from "
3089 + bp.sourcePackage);
3090 }
3091 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3092 if (r == null) {
3093 r = new StringBuilder(256);
3094 } else {
3095 r.append(' ');
3096 }
3097 r.append("DUP:");
3098 r.append(p.info.name);
3099 }
3100 } else {
3101 Log.w(TAG, "Permission " + p.info.name + " from package "
3102 + p.info.packageName + " ignored: no group "
3103 + p.group);
3104 }
3105 }
3106 if (r != null) {
3107 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 N = pkg.instrumentation.size();
3111 r = null;
3112 for (i=0; i<N; i++) {
3113 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3114 a.info.packageName = pkg.applicationInfo.packageName;
3115 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3116 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3117 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003118 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3120 if (r == null) {
3121 r = new StringBuilder(256);
3122 } else {
3123 r.append(' ');
3124 }
3125 r.append(a.info.name);
3126 }
3127 }
3128 if (r != null) {
3129 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003131
Dianne Hackborn854060af2009-07-09 18:14:31 -07003132 if (pkg.protectedBroadcasts != null) {
3133 N = pkg.protectedBroadcasts.size();
3134 for (i=0; i<N; i++) {
3135 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3136 }
3137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 pkgSetting.setTimeStamp(scanFileTime);
3140 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 return pkg;
3143 }
3144
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003145 private void killApplication(String pkgName, int uid) {
3146 // Request the ActivityManager to kill the process(only for existing packages)
3147 // so that we do not end up in a confused state while the user is still using the older
3148 // version of the application while the new one gets installed.
3149 IActivityManager am = ActivityManagerNative.getDefault();
3150 if (am != null) {
3151 try {
3152 am.killApplicationWithUid(pkgName, uid);
3153 } catch (RemoteException e) {
3154 }
3155 }
3156 }
3157
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003158 // The following constants are returned by cachePackageSharedLibsForAbiLI
3159 // to indicate if native shared libraries were found in the package.
3160 // Values are:
3161 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3162 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3163 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3164 // in package (and not installed)
3165 //
3166 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3167 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3168 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003170 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3171 // and automatically copy them to /data/data/<appname>/lib if present.
3172 //
3173 // NOTE: this method may throw an IOException if the library cannot
3174 // be copied to its final destination, e.g. if there isn't enough
3175 // room left on the data partition, or a ZipException if the package
3176 // file is malformed.
3177 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003178 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3179 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003180 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3181 final String apkLib = "lib/";
3182 final int apkLibLen = apkLib.length();
3183 final int cpuAbiLen = cpuAbi.length();
3184 final String libPrefix = "lib";
3185 final int libPrefixLen = libPrefix.length();
3186 final String libSuffix = ".so";
3187 final int libSuffixLen = libSuffix.length();
3188 boolean hasNativeLibraries = false;
3189 boolean installedNativeLibraries = false;
3190
3191 // the minimum length of a valid native shared library of the form
3192 // lib/<something>/lib<name>.so.
3193 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3194
3195 ZipFile zipFile = new ZipFile(scanFile);
3196 Enumeration<ZipEntry> entries =
3197 (Enumeration<ZipEntry>) zipFile.entries();
3198
3199 while (entries.hasMoreElements()) {
3200 ZipEntry entry = entries.nextElement();
3201 // skip directories
3202 if (entry.isDirectory()) {
3203 continue;
3204 }
3205 String entryName = entry.getName();
3206
3207 // check that the entry looks like lib/<something>/lib<name>.so
3208 // here, but don't check the ABI just yet.
3209 //
3210 // - must be sufficiently long
3211 // - must end with libSuffix, i.e. ".so"
3212 // - must start with apkLib, i.e. "lib/"
3213 if (entryName.length() < minEntryLen ||
3214 !entryName.endsWith(libSuffix) ||
3215 !entryName.startsWith(apkLib) ) {
3216 continue;
3217 }
3218
3219 // file name must start with libPrefix, i.e. "lib"
3220 int lastSlash = entryName.lastIndexOf('/');
3221
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003222 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003223 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3224 continue;
3225 }
3226
3227 hasNativeLibraries = true;
3228
3229 // check the cpuAbi now, between lib/ and /lib<name>.so
3230 //
3231 if (lastSlash != apkLibLen + cpuAbiLen ||
3232 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3233 continue;
3234
3235 // extract the library file name, ensure it doesn't contain
3236 // weird characters. we're guaranteed here that it doesn't contain
3237 // a directory separator though.
3238 String libFileName = entryName.substring(lastSlash+1);
3239 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3240 continue;
3241 }
3242
3243 installedNativeLibraries = true;
3244
3245 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3246 File.separator + libFileName;
3247 File sharedLibraryFile = new File(sharedLibraryFilePath);
3248 if (! sharedLibraryFile.exists() ||
3249 sharedLibraryFile.length() != entry.getSize() ||
3250 sharedLibraryFile.lastModified() != entry.getTime()) {
3251 if (Config.LOGD) {
3252 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003254 if (mInstaller == null) {
3255 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003256 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003257 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003258 sharedLibraryFile);
3259 }
3260 }
3261 if (!hasNativeLibraries)
3262 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3263
3264 if (!installedNativeLibraries)
3265 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3266
3267 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3268 }
3269
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003270 // Find the gdbserver executable program in a package at
3271 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3272 //
3273 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3274 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3275 //
3276 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3277 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3278 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3279 final String GDBSERVER = "gdbserver";
3280 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3281
3282 ZipFile zipFile = new ZipFile(scanFile);
3283 Enumeration<ZipEntry> entries =
3284 (Enumeration<ZipEntry>) zipFile.entries();
3285
3286 while (entries.hasMoreElements()) {
3287 ZipEntry entry = entries.nextElement();
3288 // skip directories
3289 if (entry.isDirectory()) {
3290 continue;
3291 }
3292 String entryName = entry.getName();
3293
3294 if (!entryName.equals(apkGdbServerPath)) {
3295 continue;
3296 }
3297
3298 String installGdbServerPath = installGdbServerDir.getPath() +
3299 "/" + GDBSERVER;
3300 File installGdbServerFile = new File(installGdbServerPath);
3301 if (! installGdbServerFile.exists() ||
3302 installGdbServerFile.length() != entry.getSize() ||
3303 installGdbServerFile.lastModified() != entry.getTime()) {
3304 if (Config.LOGD) {
3305 Log.d(TAG, "Caching gdbserver " + entry.getName());
3306 }
3307 if (mInstaller == null) {
3308 installGdbServerDir.mkdir();
3309 }
3310 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3311 installGdbServerFile);
3312 }
3313 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3314 }
3315 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3316 }
3317
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003318 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3319 // and copy them to /data/data/<appname>/lib.
3320 //
3321 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3322 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3323 // one if ro.product.cpu.abi2 is defined.
3324 //
3325 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3326 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003327 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003328 try {
3329 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3330
3331 // some architectures are capable of supporting several CPU ABIs
3332 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3333 // this is indicated by the definition of the ro.product.cpu.abi2
3334 // system property.
3335 //
3336 // only scan the package twice in case of ABI mismatch
3337 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003338 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003339 if (cpuAbi2 != null) {
3340 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003342
3343 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3344 Log.w(TAG,"Native ABI mismatch from package file");
3345 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003347
3348 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3349 cpuAbi = cpuAbi2;
3350 }
3351 }
3352
3353 // for debuggable packages, also extract gdbserver from lib/<abi>
3354 // into /data/data/<appname>/lib too.
3355 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3356 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3357 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3358 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3359 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003362 } catch (ZipException e) {
3363 Log.w(TAG, "Failed to extract data from package file", e);
3364 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003366 Log.w(TAG, "Failed to cache package shared libs", e);
3367 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003369 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 }
3371
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003372 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003374 File binaryDir,
3375 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 InputStream inputStream = zipFile.getInputStream(entry);
3377 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003378 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003380 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 // now need to be left as world readable and owned by the system.
3382 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3383 ! tempFile.setLastModified(entry.getTime()) ||
3384 FileUtils.setPermissions(tempFilePath,
3385 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003386 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003388 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 // Failed to properly write file.
3390 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003391 throw new IOException("Couldn't create cached binary "
3392 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 }
3394 } finally {
3395 inputStream.close();
3396 }
3397 }
3398
3399 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3400 if (chatty && Config.LOGD) Log.d(
3401 TAG, "Removing package " + pkg.applicationInfo.packageName );
3402
3403 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 mPackages.remove(pkg.applicationInfo.packageName);
3407 if (pkg.mPath != null) {
3408 mAppDirs.remove(pkg.mPath);
3409 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 PackageSetting ps = (PackageSetting)pkg.mExtras;
3412 if (ps != null && ps.sharedUser != null) {
3413 // XXX don't do this until the data is removed.
3414 if (false) {
3415 ps.sharedUser.packages.remove(ps);
3416 if (ps.sharedUser.packages.size() == 0) {
3417 // Remove.
3418 }
3419 }
3420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 int N = pkg.providers.size();
3423 StringBuilder r = null;
3424 int i;
3425 for (i=0; i<N; i++) {
3426 PackageParser.Provider p = pkg.providers.get(i);
3427 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3428 p.info.name));
3429 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 /* The is another ContentProvider with this authority when
3432 * this app was installed so this authority is null,
3433 * Ignore it as we don't have to unregister the provider.
3434 */
3435 continue;
3436 }
3437 String names[] = p.info.authority.split(";");
3438 for (int j = 0; j < names.length; j++) {
3439 if (mProviders.get(names[j]) == p) {
3440 mProviders.remove(names[j]);
3441 if (chatty && Config.LOGD) Log.d(
3442 TAG, "Unregistered content provider: " + names[j] +
3443 ", className = " + p.info.name +
3444 ", isSyncable = " + p.info.isSyncable);
3445 }
3446 }
3447 if (chatty) {
3448 if (r == null) {
3449 r = new StringBuilder(256);
3450 } else {
3451 r.append(' ');
3452 }
3453 r.append(p.info.name);
3454 }
3455 }
3456 if (r != null) {
3457 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3458 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 N = pkg.services.size();
3461 r = null;
3462 for (i=0; i<N; i++) {
3463 PackageParser.Service s = pkg.services.get(i);
3464 mServices.removeService(s);
3465 if (chatty) {
3466 if (r == null) {
3467 r = new StringBuilder(256);
3468 } else {
3469 r.append(' ');
3470 }
3471 r.append(s.info.name);
3472 }
3473 }
3474 if (r != null) {
3475 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 N = pkg.receivers.size();
3479 r = null;
3480 for (i=0; i<N; i++) {
3481 PackageParser.Activity a = pkg.receivers.get(i);
3482 mReceivers.removeActivity(a, "receiver");
3483 if (chatty) {
3484 if (r == null) {
3485 r = new StringBuilder(256);
3486 } else {
3487 r.append(' ');
3488 }
3489 r.append(a.info.name);
3490 }
3491 }
3492 if (r != null) {
3493 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3494 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 N = pkg.activities.size();
3497 r = null;
3498 for (i=0; i<N; i++) {
3499 PackageParser.Activity a = pkg.activities.get(i);
3500 mActivities.removeActivity(a, "activity");
3501 if (chatty) {
3502 if (r == null) {
3503 r = new StringBuilder(256);
3504 } else {
3505 r.append(' ');
3506 }
3507 r.append(a.info.name);
3508 }
3509 }
3510 if (r != null) {
3511 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 N = pkg.permissions.size();
3515 r = null;
3516 for (i=0; i<N; i++) {
3517 PackageParser.Permission p = pkg.permissions.get(i);
3518 boolean tree = false;
3519 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3520 if (bp == null) {
3521 tree = true;
3522 bp = mSettings.mPermissionTrees.get(p.info.name);
3523 }
3524 if (bp != null && bp.perm == p) {
3525 if (bp.type != BasePermission.TYPE_BUILTIN) {
3526 if (tree) {
3527 mSettings.mPermissionTrees.remove(p.info.name);
3528 } else {
3529 mSettings.mPermissions.remove(p.info.name);
3530 }
3531 } else {
3532 bp.perm = null;
3533 }
3534 if (chatty) {
3535 if (r == null) {
3536 r = new StringBuilder(256);
3537 } else {
3538 r.append(' ');
3539 }
3540 r.append(p.info.name);
3541 }
3542 }
3543 }
3544 if (r != null) {
3545 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 N = pkg.instrumentation.size();
3549 r = null;
3550 for (i=0; i<N; i++) {
3551 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003552 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 if (chatty) {
3554 if (r == null) {
3555 r = new StringBuilder(256);
3556 } else {
3557 r.append(' ');
3558 }
3559 r.append(a.info.name);
3560 }
3561 }
3562 if (r != null) {
3563 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3564 }
3565 }
3566 }
3567
3568 private static final boolean isPackageFilename(String name) {
3569 return name != null && name.endsWith(".apk");
3570 }
3571
3572 private void updatePermissionsLP() {
3573 // Make sure there are no dangling permission trees.
3574 Iterator<BasePermission> it = mSettings.mPermissionTrees
3575 .values().iterator();
3576 while (it.hasNext()) {
3577 BasePermission bp = it.next();
3578 if (bp.perm == null) {
3579 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3580 + " from package " + bp.sourcePackage);
3581 it.remove();
3582 }
3583 }
3584
3585 // Make sure all dynamic permissions have been assigned to a package,
3586 // and make sure there are no dangling permissions.
3587 it = mSettings.mPermissions.values().iterator();
3588 while (it.hasNext()) {
3589 BasePermission bp = it.next();
3590 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3591 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3592 + bp.name + " pkg=" + bp.sourcePackage
3593 + " info=" + bp.pendingInfo);
3594 if (bp.perm == null && bp.pendingInfo != null) {
3595 BasePermission tree = findPermissionTreeLP(bp.name);
3596 if (tree != null) {
3597 bp.perm = new PackageParser.Permission(tree.perm.owner,
3598 new PermissionInfo(bp.pendingInfo));
3599 bp.perm.info.packageName = tree.perm.info.packageName;
3600 bp.perm.info.name = bp.name;
3601 bp.uid = tree.uid;
3602 }
3603 }
3604 }
3605 if (bp.perm == null) {
3606 Log.w(TAG, "Removing dangling permission: " + bp.name
3607 + " from package " + bp.sourcePackage);
3608 it.remove();
3609 }
3610 }
3611
3612 // Now update the permissions for all packages, in particular
3613 // replace the granted permissions of the system packages.
3614 for (PackageParser.Package pkg : mPackages.values()) {
3615 grantPermissionsLP(pkg, false);
3616 }
3617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3620 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3621 if (ps == null) {
3622 return;
3623 }
3624 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3625 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 if (replace) {
3628 ps.permissionsFixed = false;
3629 if (gp == ps) {
3630 gp.grantedPermissions.clear();
3631 gp.gids = mGlobalGids;
3632 }
3633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 if (gp.gids == null) {
3636 gp.gids = mGlobalGids;
3637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003639 final int N = pkg.requestedPermissions.size();
3640 for (int i=0; i<N; i++) {
3641 String name = pkg.requestedPermissions.get(i);
3642 BasePermission bp = mSettings.mPermissions.get(name);
3643 PackageParser.Permission p = bp != null ? bp.perm : null;
3644 if (false) {
3645 if (gp != ps) {
3646 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3647 + ": " + p);
3648 }
3649 }
3650 if (p != null) {
3651 final String perm = p.info.name;
3652 boolean allowed;
3653 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3654 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3655 allowed = true;
3656 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3657 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003658 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003660 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 == PackageManager.SIGNATURE_MATCH);
3662 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3663 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3664 // For updated system applications, the signatureOrSystem permission
3665 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003666 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3668 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3669 if(sysPs.grantedPermissions.contains(perm)) {
3670 allowed = true;
3671 } else {
3672 allowed = false;
3673 }
3674 } else {
3675 allowed = true;
3676 }
3677 }
3678 }
3679 } else {
3680 allowed = false;
3681 }
3682 if (false) {
3683 if (gp != ps) {
3684 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3685 }
3686 }
3687 if (allowed) {
3688 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3689 && ps.permissionsFixed) {
3690 // If this is an existing, non-system package, then
3691 // we can't add any new permissions to it.
3692 if (!gp.loadedPermissions.contains(perm)) {
3693 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003694 // Except... if this is a permission that was added
3695 // to the platform (note: need to only do this when
3696 // updating the platform).
3697 final int NP = PackageParser.NEW_PERMISSIONS.length;
3698 for (int ip=0; ip<NP; ip++) {
3699 final PackageParser.NewPermissionInfo npi
3700 = PackageParser.NEW_PERMISSIONS[ip];
3701 if (npi.name.equals(perm)
3702 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3703 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003704 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003705 + pkg.packageName);
3706 break;
3707 }
3708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 }
3710 }
3711 if (allowed) {
3712 if (!gp.grantedPermissions.contains(perm)) {
3713 addedPermission = true;
3714 gp.grantedPermissions.add(perm);
3715 gp.gids = appendInts(gp.gids, bp.gids);
3716 }
3717 } else {
3718 Log.w(TAG, "Not granting permission " + perm
3719 + " to package " + pkg.packageName
3720 + " because it was previously installed without");
3721 }
3722 } else {
3723 Log.w(TAG, "Not granting permission " + perm
3724 + " to package " + pkg.packageName
3725 + " (protectionLevel=" + p.info.protectionLevel
3726 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3727 + ")");
3728 }
3729 } else {
3730 Log.w(TAG, "Unknown permission " + name
3731 + " in package " + pkg.packageName);
3732 }
3733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003736 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3737 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 // This is the first that we have heard about this package, so the
3739 // permissions we have now selected are fixed until explicitly
3740 // changed.
3741 ps.permissionsFixed = true;
3742 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3743 }
3744 }
3745
3746 private final class ActivityIntentResolver
3747 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003748 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003750 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 }
3752
Mihai Preda074edef2009-05-18 17:13:31 +02003753 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003755 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3757 }
3758
Mihai Predaeae850c2009-05-13 10:13:48 +02003759 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3760 ArrayList<PackageParser.Activity> packageActivities) {
3761 if (packageActivities == null) {
3762 return null;
3763 }
3764 mFlags = flags;
3765 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3766 int N = packageActivities.size();
3767 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3768 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003769
3770 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003771 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003772 intentFilters = packageActivities.get(i).intents;
3773 if (intentFilters != null && intentFilters.size() > 0) {
3774 listCut.add(intentFilters);
3775 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003776 }
3777 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3778 }
3779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003781 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 if (SHOW_INFO || Config.LOGV) Log.v(
3783 TAG, " " + type + " " +
3784 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3785 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3786 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003787 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3789 if (SHOW_INFO || Config.LOGV) {
3790 Log.v(TAG, " IntentFilter:");
3791 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3792 }
3793 if (!intent.debugCheck()) {
3794 Log.w(TAG, "==> For Activity " + a.info.name);
3795 }
3796 addFilter(intent);
3797 }
3798 }
3799
3800 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003801 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 if (SHOW_INFO || Config.LOGV) Log.v(
3803 TAG, " " + type + " " +
3804 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3805 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3806 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003807 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3809 if (SHOW_INFO || Config.LOGV) {
3810 Log.v(TAG, " IntentFilter:");
3811 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3812 }
3813 removeFilter(intent);
3814 }
3815 }
3816
3817 @Override
3818 protected boolean allowFilterResult(
3819 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3820 ActivityInfo filterAi = filter.activity.info;
3821 for (int i=dest.size()-1; i>=0; i--) {
3822 ActivityInfo destAi = dest.get(i).activityInfo;
3823 if (destAi.name == filterAi.name
3824 && destAi.packageName == filterAi.packageName) {
3825 return false;
3826 }
3827 }
3828 return true;
3829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 @Override
3832 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3833 int match) {
3834 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3835 return null;
3836 }
3837 final PackageParser.Activity activity = info.activity;
3838 if (mSafeMode && (activity.info.applicationInfo.flags
3839 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3840 return null;
3841 }
3842 final ResolveInfo res = new ResolveInfo();
3843 res.activityInfo = PackageParser.generateActivityInfo(activity,
3844 mFlags);
3845 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3846 res.filter = info;
3847 }
3848 res.priority = info.getPriority();
3849 res.preferredOrder = activity.owner.mPreferredOrder;
3850 //System.out.println("Result: " + res.activityInfo.className +
3851 // " = " + res.priority);
3852 res.match = match;
3853 res.isDefault = info.hasDefault;
3854 res.labelRes = info.labelRes;
3855 res.nonLocalizedLabel = info.nonLocalizedLabel;
3856 res.icon = info.icon;
3857 return res;
3858 }
3859
3860 @Override
3861 protected void sortResults(List<ResolveInfo> results) {
3862 Collections.sort(results, mResolvePrioritySorter);
3863 }
3864
3865 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003866 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003868 out.print(prefix); out.print(
3869 Integer.toHexString(System.identityHashCode(filter.activity)));
3870 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003871 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 }
3873
3874// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3875// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3876// final List<ResolveInfo> retList = Lists.newArrayList();
3877// while (i.hasNext()) {
3878// final ResolveInfo resolveInfo = i.next();
3879// if (isEnabledLP(resolveInfo.activityInfo)) {
3880// retList.add(resolveInfo);
3881// }
3882// }
3883// return retList;
3884// }
3885
3886 // Keys are String (activity class name), values are Activity.
3887 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3888 = new HashMap<ComponentName, PackageParser.Activity>();
3889 private int mFlags;
3890 }
3891
3892 private final class ServiceIntentResolver
3893 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003894 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003896 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
3898
Mihai Preda074edef2009-05-18 17:13:31 +02003899 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003901 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3903 }
3904
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003905 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3906 ArrayList<PackageParser.Service> packageServices) {
3907 if (packageServices == null) {
3908 return null;
3909 }
3910 mFlags = flags;
3911 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3912 int N = packageServices.size();
3913 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3914 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3915
3916 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3917 for (int i = 0; i < N; ++i) {
3918 intentFilters = packageServices.get(i).intents;
3919 if (intentFilters != null && intentFilters.size() > 0) {
3920 listCut.add(intentFilters);
3921 }
3922 }
3923 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3924 }
3925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003927 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 if (SHOW_INFO || Config.LOGV) Log.v(
3929 TAG, " " + (s.info.nonLocalizedLabel != null
3930 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3931 if (SHOW_INFO || Config.LOGV) Log.v(
3932 TAG, " Class=" + s.info.name);
3933 int NI = s.intents.size();
3934 int j;
3935 for (j=0; j<NI; j++) {
3936 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3937 if (SHOW_INFO || Config.LOGV) {
3938 Log.v(TAG, " IntentFilter:");
3939 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3940 }
3941 if (!intent.debugCheck()) {
3942 Log.w(TAG, "==> For Service " + s.info.name);
3943 }
3944 addFilter(intent);
3945 }
3946 }
3947
3948 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003949 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 if (SHOW_INFO || Config.LOGV) Log.v(
3951 TAG, " " + (s.info.nonLocalizedLabel != null
3952 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3953 if (SHOW_INFO || Config.LOGV) Log.v(
3954 TAG, " Class=" + s.info.name);
3955 int NI = s.intents.size();
3956 int j;
3957 for (j=0; j<NI; j++) {
3958 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3959 if (SHOW_INFO || Config.LOGV) {
3960 Log.v(TAG, " IntentFilter:");
3961 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3962 }
3963 removeFilter(intent);
3964 }
3965 }
3966
3967 @Override
3968 protected boolean allowFilterResult(
3969 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3970 ServiceInfo filterSi = filter.service.info;
3971 for (int i=dest.size()-1; i>=0; i--) {
3972 ServiceInfo destAi = dest.get(i).serviceInfo;
3973 if (destAi.name == filterSi.name
3974 && destAi.packageName == filterSi.packageName) {
3975 return false;
3976 }
3977 }
3978 return true;
3979 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 @Override
3982 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3983 int match) {
3984 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3985 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3986 return null;
3987 }
3988 final PackageParser.Service service = info.service;
3989 if (mSafeMode && (service.info.applicationInfo.flags
3990 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3991 return null;
3992 }
3993 final ResolveInfo res = new ResolveInfo();
3994 res.serviceInfo = PackageParser.generateServiceInfo(service,
3995 mFlags);
3996 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3997 res.filter = filter;
3998 }
3999 res.priority = info.getPriority();
4000 res.preferredOrder = service.owner.mPreferredOrder;
4001 //System.out.println("Result: " + res.activityInfo.className +
4002 // " = " + res.priority);
4003 res.match = match;
4004 res.isDefault = info.hasDefault;
4005 res.labelRes = info.labelRes;
4006 res.nonLocalizedLabel = info.nonLocalizedLabel;
4007 res.icon = info.icon;
4008 return res;
4009 }
4010
4011 @Override
4012 protected void sortResults(List<ResolveInfo> results) {
4013 Collections.sort(results, mResolvePrioritySorter);
4014 }
4015
4016 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004017 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004019 out.print(prefix); out.print(
4020 Integer.toHexString(System.identityHashCode(filter.service)));
4021 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004022 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 }
4024
4025// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4026// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4027// final List<ResolveInfo> retList = Lists.newArrayList();
4028// while (i.hasNext()) {
4029// final ResolveInfo resolveInfo = (ResolveInfo) i;
4030// if (isEnabledLP(resolveInfo.serviceInfo)) {
4031// retList.add(resolveInfo);
4032// }
4033// }
4034// return retList;
4035// }
4036
4037 // Keys are String (activity class name), values are Activity.
4038 private final HashMap<ComponentName, PackageParser.Service> mServices
4039 = new HashMap<ComponentName, PackageParser.Service>();
4040 private int mFlags;
4041 };
4042
4043 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4044 new Comparator<ResolveInfo>() {
4045 public int compare(ResolveInfo r1, ResolveInfo r2) {
4046 int v1 = r1.priority;
4047 int v2 = r2.priority;
4048 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4049 if (v1 != v2) {
4050 return (v1 > v2) ? -1 : 1;
4051 }
4052 v1 = r1.preferredOrder;
4053 v2 = r2.preferredOrder;
4054 if (v1 != v2) {
4055 return (v1 > v2) ? -1 : 1;
4056 }
4057 if (r1.isDefault != r2.isDefault) {
4058 return r1.isDefault ? -1 : 1;
4059 }
4060 v1 = r1.match;
4061 v2 = r2.match;
4062 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4063 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4064 }
4065 };
4066
4067 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4068 new Comparator<ProviderInfo>() {
4069 public int compare(ProviderInfo p1, ProviderInfo p2) {
4070 final int v1 = p1.initOrder;
4071 final int v2 = p2.initOrder;
4072 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4073 }
4074 };
4075
4076 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4077 IActivityManager am = ActivityManagerNative.getDefault();
4078 if (am != null) {
4079 try {
4080 final Intent intent = new Intent(action,
4081 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4082 if (extras != null) {
4083 intent.putExtras(extras);
4084 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004085 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 am.broadcastIntent(
4087 null, intent,
4088 null, null, 0, null, null, null, false, false);
4089 } catch (RemoteException ex) {
4090 }
4091 }
4092 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004093
4094 public String nextPackageToClean(String lastPackage) {
4095 synchronized (mPackages) {
4096 if (!mMediaMounted) {
4097 // If the external storage is no longer mounted at this point,
4098 // the caller may not have been able to delete all of this
4099 // packages files and can not delete any more. Bail.
4100 return null;
4101 }
4102 if (lastPackage != null) {
4103 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4104 }
4105 return mSettings.mPackagesToBeCleaned.size() > 0
4106 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4107 }
4108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004110 void schedulePackageCleaning(String packageName) {
4111 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4112 }
4113
4114 void startCleaningPackages() {
4115 synchronized (mPackages) {
4116 if (!mMediaMounted) {
4117 return;
4118 }
4119 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4120 return;
4121 }
4122 }
4123 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4124 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4125 IActivityManager am = ActivityManagerNative.getDefault();
4126 if (am != null) {
4127 try {
4128 am.startService(null, intent, null);
4129 } catch (RemoteException e) {
4130 }
4131 }
4132 }
4133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 private final class AppDirObserver extends FileObserver {
4135 public AppDirObserver(String path, int mask, boolean isrom) {
4136 super(path, mask);
4137 mRootDir = path;
4138 mIsRom = isrom;
4139 }
4140
4141 public void onEvent(int event, String path) {
4142 String removedPackage = null;
4143 int removedUid = -1;
4144 String addedPackage = null;
4145 int addedUid = -1;
4146
4147 synchronized (mInstallLock) {
4148 String fullPathStr = null;
4149 File fullPath = null;
4150 if (path != null) {
4151 fullPath = new File(mRootDir, path);
4152 fullPathStr = fullPath.getPath();
4153 }
4154
4155 if (Config.LOGV) Log.v(
4156 TAG, "File " + fullPathStr + " changed: "
4157 + Integer.toHexString(event));
4158
4159 if (!isPackageFilename(path)) {
4160 if (Config.LOGV) Log.v(
4161 TAG, "Ignoring change of non-package file: " + fullPathStr);
4162 return;
4163 }
4164
4165 if ((event&REMOVE_EVENTS) != 0) {
4166 synchronized (mInstallLock) {
4167 PackageParser.Package p = mAppDirs.get(fullPathStr);
4168 if (p != null) {
4169 removePackageLI(p, true);
4170 removedPackage = p.applicationInfo.packageName;
4171 removedUid = p.applicationInfo.uid;
4172 }
4173 }
4174 }
4175
4176 if ((event&ADD_EVENTS) != 0) {
4177 PackageParser.Package p = mAppDirs.get(fullPathStr);
4178 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004179 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4181 PackageParser.PARSE_CHATTY |
4182 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004183 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 if (p != null) {
4185 synchronized (mPackages) {
4186 grantPermissionsLP(p, false);
4187 }
4188 addedPackage = p.applicationInfo.packageName;
4189 addedUid = p.applicationInfo.uid;
4190 }
4191 }
4192 }
4193
4194 synchronized (mPackages) {
4195 mSettings.writeLP();
4196 }
4197 }
4198
4199 if (removedPackage != null) {
4200 Bundle extras = new Bundle(1);
4201 extras.putInt(Intent.EXTRA_UID, removedUid);
4202 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4203 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4204 }
4205 if (addedPackage != null) {
4206 Bundle extras = new Bundle(1);
4207 extras.putInt(Intent.EXTRA_UID, addedUid);
4208 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4209 }
4210 }
4211
4212 private final String mRootDir;
4213 private final boolean mIsRom;
4214 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 /* Called when a downloaded package installation has been confirmed by the user */
4217 public void installPackage(
4218 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004219 installPackage(packageURI, observer, flags, null);
4220 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004221
Jacek Surazski65e13172009-04-28 15:26:38 +02004222 /* Called when a downloaded package installation has been confirmed by the user */
4223 public void installPackage(
4224 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4225 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 mContext.enforceCallingOrSelfPermission(
4227 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004228
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004229 Message msg = mHandler.obtainMessage(INIT_COPY);
4230 msg.obj = createInstallArgs(packageURI, observer, flags, installerPackageName);
4231 mHandler.sendMessage(msg);
4232 }
4233
4234 private InstallArgs createInstallArgs(Uri packageURI, IPackageInstallObserver observer,
4235 int flags, String installerPackageName) {
4236 if (installOnSd(flags)) {
4237 return new SdInstallArgs(packageURI, observer, flags,
4238 installerPackageName);
4239 } else {
4240 return new FileInstallArgs(packageURI, observer, flags,
4241 installerPackageName);
4242 }
4243 }
4244
4245 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4246 if (installOnSd(flags)) {
4247 return new SdInstallArgs(fullCodePath, fullResourcePath);
4248 } else {
4249 return new FileInstallArgs(fullCodePath, fullResourcePath);
4250 }
4251 }
4252
4253 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 // Queue up an async operation since the package installation may take a little while.
4255 mHandler.post(new Runnable() {
4256 public void run() {
4257 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004258 // Result object to be returned
4259 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004260 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004261 res.uid = -1;
4262 res.pkg = null;
4263 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004264 args.doPreInstall(res.returnCode);
4265 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004266 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004267 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004268 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004269 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004271 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004273 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274 } catch (RemoteException e) {
4275 Log.i(TAG, "Observer no longer exists.");
4276 }
4277 }
4278 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4279 // call appears in the synchronized block above.
4280 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4281 res.removedInfo.sendBroadcast(false, true);
4282 Bundle extras = new Bundle(1);
4283 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004284 final boolean update = res.removedInfo.removedPackage != null;
4285 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4287 }
4288 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4289 res.pkg.applicationInfo.packageName,
4290 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004291 if (update) {
4292 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4293 res.pkg.applicationInfo.packageName,
4294 extras);
4295 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004296 if (res.removedInfo.args != null) {
4297 // Remove the replaced package's older resources safely now
4298 synchronized (mInstallLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004299 res.removedInfo.args.doPostDeleteLI(true);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004300 }
4301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 }
4303 Runtime.getRuntime().gc();
4304 }
4305 });
4306 }
4307
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004308 static abstract class InstallArgs {
4309 final IPackageInstallObserver observer;
4310 final int flags;
4311 final Uri packageURI;
4312 final String installerPackageName;
4313
4314 InstallArgs(Uri packageURI,
4315 IPackageInstallObserver observer, int flags,
4316 String installerPackageName) {
4317 this.packageURI = packageURI;
4318 this.flags = flags;
4319 this.observer = observer;
4320 this.installerPackageName = installerPackageName;
4321 }
4322
4323 abstract void createCopyFile();
4324 abstract int copyApk(IMediaContainerService imcs);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004325 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004326 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004327 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004328 abstract String getCodePath();
4329 abstract String getResourcePath();
4330 // Need installer lock especially for dex file removal.
4331 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004332 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004333 }
4334
4335 class FileInstallArgs extends InstallArgs {
4336 File installDir;
4337 String codeFileName;
4338 String resourceFileName;
4339
4340 FileInstallArgs(Uri packageURI,
4341 IPackageInstallObserver observer, int flags,
4342 String installerPackageName) {
4343 super(packageURI, observer, flags, installerPackageName);
4344 }
4345
4346 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4347 super(null, null, 0, null);
4348 File codeFile = new File(fullCodePath);
4349 installDir = codeFile.getParentFile();
4350 codeFileName = fullCodePath;
4351 resourceFileName = fullResourcePath;
4352 }
4353
4354 void createCopyFile() {
4355 boolean fwdLocked = isFwdLocked(flags);
4356 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4357 codeFileName = createTempPackageFile(installDir).getPath();
4358 resourceFileName = getResourcePathFromCodePath();
4359 }
4360
4361 String getCodePath() {
4362 return codeFileName;
4363 }
4364
4365 int copyApk(IMediaContainerService imcs) {
4366 // Get a ParcelFileDescriptor to write to the output file
4367 File codeFile = new File(codeFileName);
4368 ParcelFileDescriptor out = null;
4369 try {
4370 out = ParcelFileDescriptor.open(codeFile,
4371 ParcelFileDescriptor.MODE_READ_WRITE);
4372 } catch (FileNotFoundException e) {
4373 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4374 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4375 }
4376 // Copy the resource now
4377 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4378 try {
4379 if (imcs.copyResource(packageURI, out)) {
4380 ret = PackageManager.INSTALL_SUCCEEDED;
4381 }
4382 } catch (RemoteException e) {
4383 } finally {
4384 try { if (out != null) out.close(); } catch (IOException e) {}
4385 }
4386 return ret;
4387 }
4388
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004389 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004390 if (status != PackageManager.INSTALL_SUCCEEDED) {
4391 cleanUp();
4392 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004393 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004394 }
4395
4396 boolean doRename(int status, final String pkgName, String oldCodePath) {
4397 if (status != PackageManager.INSTALL_SUCCEEDED) {
4398 cleanUp();
4399 return false;
4400 } else {
4401 // Rename based on packageName
4402 File codeFile = new File(getCodePath());
4403 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4404 File desFile = new File(installDir, apkName + ".apk");
4405 if (!codeFile.renameTo(desFile)) {
4406 return false;
4407 }
4408 // Reset paths since the file has been renamed.
4409 codeFileName = desFile.getPath();
4410 resourceFileName = getResourcePathFromCodePath();
4411 // Set permissions
4412 if (!setPermissions(pkgName)) {
4413 // Failed setting permissions.
4414 return false;
4415 }
4416 return true;
4417 }
4418 }
4419
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004420 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004421 if (status != PackageManager.INSTALL_SUCCEEDED) {
4422 cleanUp();
4423 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004424 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004425 }
4426
4427 String getResourcePath() {
4428 return resourceFileName;
4429 }
4430
4431 String getResourcePathFromCodePath() {
4432 String codePath = getCodePath();
4433 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4434 String apkNameOnly = getApkName(codePath);
4435 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4436 } else {
4437 return codePath;
4438 }
4439 }
4440
4441 private boolean cleanUp() {
4442 boolean ret = true;
4443 String sourceDir = getCodePath();
4444 String publicSourceDir = getResourcePath();
4445 if (sourceDir != null) {
4446 File sourceFile = new File(sourceDir);
4447 if (!sourceFile.exists()) {
4448 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4449 ret = false;
4450 }
4451 // Delete application's code and resources
4452 sourceFile.delete();
4453 }
4454 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4455 final File publicSourceFile = new File(publicSourceDir);
4456 if (!publicSourceFile.exists()) {
4457 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4458 }
4459 if (publicSourceFile.exists()) {
4460 publicSourceFile.delete();
4461 }
4462 }
4463 return ret;
4464 }
4465
4466 void cleanUpResourcesLI() {
4467 String sourceDir = getCodePath();
4468 if (cleanUp() && mInstaller != null) {
4469 int retCode = mInstaller.rmdex(sourceDir);
4470 if (retCode < 0) {
4471 Log.w(TAG, "Couldn't remove dex file for package: "
4472 + " at location "
4473 + sourceDir + ", retcode=" + retCode);
4474 // we don't consider this to be a failure of the core package deletion
4475 }
4476 }
4477 }
4478
4479 private boolean setPermissions(String pkgName) {
4480 // TODO Do this in a more elegant way later on. for now just a hack
4481 if (!isFwdLocked(flags)) {
4482 final int filePermissions =
4483 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4484 |FileUtils.S_IROTH;
4485 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4486 if (retCode != 0) {
4487 Log.e(TAG, "Couldn't set new package file permissions for " +
4488 getCodePath()
4489 + ". The return code was: " + retCode);
4490 // TODO Define new internal error
4491 return false;
4492 }
4493 return true;
4494 }
4495 return true;
4496 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004497
4498 boolean doPostDeleteLI(boolean delete) {
4499 cleanUpResourcesLI();
4500 return true;
4501 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004502 }
4503
4504 class SdInstallArgs extends InstallArgs {
4505 String cid;
4506 String cachePath;
4507 static final String RES_FILE_NAME = "pkg.apk";
4508
4509 SdInstallArgs(Uri packageURI,
4510 IPackageInstallObserver observer, int flags,
4511 String installerPackageName) {
4512 super(packageURI, observer, flags, installerPackageName);
4513 }
4514
4515 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004516 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004517 // Extract cid from fullCodePath
4518 int eidx = fullCodePath.lastIndexOf("/");
4519 String subStr1 = fullCodePath.substring(0, eidx);
4520 int sidx = subStr1.lastIndexOf("/");
4521 cid = subStr1.substring(sidx+1, eidx);
4522 cachePath = subStr1;
4523 }
4524
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004525 SdInstallArgs(String cid) {
4526 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
4527 this.cid = cid;
4528 }
4529
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004530 void createCopyFile() {
4531 cid = getTempContainerId();
4532 }
4533
4534 int copyApk(IMediaContainerService imcs) {
4535 try {
4536 cachePath = imcs.copyResourceToContainer(
4537 packageURI, cid,
4538 getEncryptKey(), RES_FILE_NAME);
4539 } catch (RemoteException e) {
4540 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004541 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4542 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004543 }
4544
4545 @Override
4546 String getCodePath() {
4547 return cachePath + "/" + RES_FILE_NAME;
4548 }
4549
4550 @Override
4551 String getResourcePath() {
4552 return cachePath + "/" + RES_FILE_NAME;
4553 }
4554
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004555 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004556 if (status != PackageManager.INSTALL_SUCCEEDED) {
4557 // Destroy container
4558 destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004559 } else {
4560 // STOPSHIP Remove once new api is added in MountService
4561 //boolean mounted = isContainerMounted(cid);
4562 boolean mounted = false;
4563 if (!mounted) {
4564 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4565 if (cachePath == null) {
4566 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4567 }
4568 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004569 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004570 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004571 }
4572
4573 boolean doRename(int status, final String pkgName,
4574 String oldCodePath) {
4575 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004576 String newCachePath = null;
4577 /*final int RENAME_FAILED = 1;
4578 final int MOUNT_FAILED = 2;
4579 final int DESTROY_FAILED = 3;
4580 final int PASS = 4;
4581 int errCode = RENAME_FAILED;
4582 if (mounted) {
4583 // Unmount the container
4584 if (!unMountSdDir(cid)) {
4585 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4586 return false;
4587 }
4588 mounted = false;
4589 }
4590 if (renameSdDir(cid, newCacheId)) {
4591 errCode = MOUNT_FAILED;
4592 if ((newCachePath = mountSdDir(newCacheId, Process.SYSTEM_UID)) != null) {
4593 errCode = PASS;
4594 }
4595 }
4596 String errMsg = "";
4597 switch (errCode) {
4598 case RENAME_FAILED:
4599 errMsg = "RENAME_FAILED";
4600 break;
4601 case MOUNT_FAILED:
4602 errMsg = "MOUNT_FAILED";
4603 break;
4604 case DESTROY_FAILED:
4605 errMsg = "DESTROY_FAILED";
4606 break;
4607 default:
4608 errMsg = "PASS";
4609 break;
4610 }
4611 Log.i(TAG, "Status: " + errMsg);
4612 if (errCode != PASS) {
4613 return false;
4614 }
4615 Log.i(TAG, "Succesfully renamed " + cid + " to " +newCacheId +
4616 " at path: " + cachePath + " to new path: " + newCachePath);
4617 cid = newCacheId;
4618 cachePath = newCachePath;
4619 return true;
4620 */
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004621 // STOPSHIP TEMPORARY HACK FOR RENAME
4622 // Create new container at newCachePath
4623 String codePath = getCodePath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004624 final int CREATE_FAILED = 1;
4625 final int COPY_FAILED = 3;
4626 final int FINALIZE_FAILED = 5;
4627 final int PASS = 7;
4628 int errCode = CREATE_FAILED;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004629
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004630 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4631 errCode = COPY_FAILED;
4632 // Copy file from codePath
4633 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4634 errCode = FINALIZE_FAILED;
4635 if (finalizeSdDir(newCacheId)) {
4636 errCode = PASS;
4637 }
4638 }
4639 }
4640 // Print error based on errCode
4641 String errMsg = "";
4642 switch (errCode) {
4643 case CREATE_FAILED:
4644 errMsg = "CREATE_FAILED";
4645 break;
4646 case COPY_FAILED:
4647 errMsg = "COPY_FAILED";
4648 destroySdDir(newCacheId);
4649 break;
4650 case FINALIZE_FAILED:
4651 errMsg = "FINALIZE_FAILED";
4652 destroySdDir(newCacheId);
4653 break;
4654 default:
4655 errMsg = "PASS";
4656 break;
4657 }
4658 // Destroy the temporary container
4659 destroySdDir(cid);
4660 Log.i(TAG, "Status: " + errMsg);
4661 if (errCode != PASS) {
4662 return false;
4663 }
4664 cid = newCacheId;
4665 cachePath = newCachePath;
4666
4667 return true;
4668 }
4669
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004670 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004671 if (status != PackageManager.INSTALL_SUCCEEDED) {
4672 cleanUp();
4673 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004674 // STOP SHIP Change this once new api is added.
4675 //boolean mounted = isContainerMounted(cid);
4676 boolean mounted = false;
4677 if (!mounted) {
4678 mountSdDir(cid, Process.SYSTEM_UID);
4679 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004680 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004681 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004682 }
4683
4684 private void cleanUp() {
4685 // Destroy secure container
4686 destroySdDir(cid);
4687 }
4688
4689 void cleanUpResourcesLI() {
4690 String sourceFile = getCodePath();
4691 // Remove dex file
4692 if (mInstaller != null) {
4693 int retCode = mInstaller.rmdex(sourceFile.toString());
4694 if (retCode < 0) {
4695 Log.w(TAG, "Couldn't remove dex file for package: "
4696 + " at location "
4697 + sourceFile.toString() + ", retcode=" + retCode);
4698 // we don't consider this to be a failure of the core package deletion
4699 }
4700 }
4701 cleanUp();
4702 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004703
4704 boolean matchContainer(String app) {
4705 if (cid.startsWith(app)) {
4706 return true;
4707 }
4708 return false;
4709 }
4710
4711 String getPackageName() {
4712 int idx = cid.lastIndexOf("-");
4713 if (idx == -1) {
4714 return cid;
4715 }
4716 return cid.substring(0, idx);
4717 }
4718
4719 boolean doPostDeleteLI(boolean delete) {
4720 boolean ret = false;
4721 boolean mounted = isContainerMounted(cid);
4722 if (mounted) {
4723 // Unmount first
4724 ret = unMountSdDir(cid);
4725 }
4726 if (ret && delete) {
4727 cleanUpResourcesLI();
4728 }
4729 return ret;
4730 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004731 };
4732
4733 // Utility method used to create code paths based on package name and available index.
4734 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4735 String idxStr = "";
4736 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004737 // Fall back to default value of idx=1 if prefix is not
4738 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004739 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004740 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004741 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004742 if (subStr.endsWith(suffix)) {
4743 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004744 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004745 // If oldCodePath already contains prefix find out the
4746 // ending index to either increment or decrement.
4747 int sidx = subStr.lastIndexOf(prefix);
4748 if (sidx != -1) {
4749 subStr = subStr.substring(sidx + prefix.length());
4750 if (subStr != null) {
4751 if (subStr.startsWith("-")) {
4752 subStr = subStr.substring(1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004753 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004754 try {
4755 idx = Integer.parseInt(subStr);
4756 if (idx <= 1) {
4757 idx++;
4758 } else {
4759 idx--;
4760 }
4761 } catch(NumberFormatException e) {
4762 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004763 }
4764 }
4765 }
4766 idxStr = "-" + Integer.toString(idx);
4767 return prefix + idxStr;
4768 }
4769
4770 // Utility method that returns the relative package path with respect
4771 // to the installation directory. Like say for /data/data/com.test-1.apk
4772 // string com.test-1 is returned.
4773 static String getApkName(String codePath) {
4774 if (codePath == null) {
4775 return null;
4776 }
4777 int sidx = codePath.lastIndexOf("/");
4778 int eidx = codePath.lastIndexOf(".");
4779 if (eidx == -1) {
4780 eidx = codePath.length();
4781 } else if (eidx == 0) {
4782 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4783 return null;
4784 }
4785 return codePath.substring(sidx+1, eidx);
4786 }
4787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 class PackageInstalledInfo {
4789 String name;
4790 int uid;
4791 PackageParser.Package pkg;
4792 int returnCode;
4793 PackageRemovedInfo removedInfo;
4794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 /*
4797 * Install a non-existing package.
4798 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004799 private void installNewPackageLI(PackageParser.Package pkg,
4800 int parseFlags,
4801 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004802 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004804 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004805 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004806
4807 if (useEncryptedFilesystemForPackage(pkg)) {
4808 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4809 } else {
4810 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 res.name = pkgName;
4813 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004814 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004816 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 + " without first uninstalling.");
4818 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4819 return;
4820 }
4821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004823 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004825 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004826 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4827 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4828 }
4829 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004830 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004831 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 res);
4833 // delete the partially installed application. the data directory will have to be
4834 // restored if it was already existing
4835 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4836 // remove package from internal structures. Note that we want deletePackageX to
4837 // delete the package data and cache directories that it created in
4838 // scanPackageLocked, unless those directories existed before we even tried to
4839 // install.
4840 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004841 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4843 res.removedInfo);
4844 }
4845 }
4846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004847
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004848 private void replacePackageLI(PackageParser.Package pkg,
4849 int parseFlags,
4850 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004851 String installerPackageName, PackageInstalledInfo res) {
4852
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004853 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004854 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004855 // First find the old package info and check signatures
4856 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004857 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004858 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004859 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004860 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4861 return;
4862 }
4863 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004864 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004865 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004866 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004868 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 }
4870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004873 PackageParser.Package pkg,
4874 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004875 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876 PackageParser.Package newPackage = null;
4877 String pkgName = deletedPackage.packageName;
4878 boolean deletedPkg = true;
4879 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004880
Jacek Surazski65e13172009-04-28 15:26:38 +02004881 String oldInstallerPackageName = null;
4882 synchronized (mPackages) {
4883 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004885
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004886 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004887 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004888 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 res.removedInfo)) {
4890 // If the existing package was'nt successfully deleted
4891 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4892 deletedPkg = false;
4893 } else {
4894 // Successfully deleted the old package. Now proceed with re-installation
4895 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004896 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004897 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004898 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4900 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004901 }
4902 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004903 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004904 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 res);
4906 updatedSettings = true;
4907 }
4908 }
4909
4910 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4911 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004912 // were keeping around in case we needed them (see below) can now be deleted.
4913 // This info will be set on the res.removedInfo to clean up later on as post
4914 // install action.
4915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 //update signature on the new package setting
4917 //this should always succeed, since we checked the
4918 //signature earlier.
4919 synchronized(mPackages) {
4920 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4921 parseFlags, true);
4922 }
4923 } else {
4924 // remove package from internal structures. Note that we want deletePackageX to
4925 // delete the package data and cache directories that it created in
4926 // scanPackageLocked, unless those directories existed before we even tried to
4927 // install.
4928 if(updatedSettings) {
4929 deletePackageLI(
4930 pkgName, true,
4931 PackageManager.DONT_DELETE_DATA,
4932 res.removedInfo);
4933 }
4934 // Since we failed to install the new package we need to restore the old
4935 // package that we deleted.
4936 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004937 File restoreFile = new File(deletedPackage.mPath);
4938 if (restoreFile == null) {
4939 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4940 return;
4941 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004942 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4943 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004944 // Parse old package
4945 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
4946 scanPackageLI(restoreFile, parseFlags, scanMode);
4947 synchronized (mPackages) {
4948 grantPermissionsLP(deletedPackage, false);
4949 mSettings.writeLP();
4950 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004951 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4952 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 }
4955 }
4956 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004958 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004959 PackageParser.Package pkg,
4960 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004961 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 PackageParser.Package newPackage = null;
4963 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004964 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 PackageParser.PARSE_IS_SYSTEM;
4966 String packageName = deletedPackage.packageName;
4967 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4968 if (packageName == null) {
4969 Log.w(TAG, "Attempt to delete null packageName.");
4970 return;
4971 }
4972 PackageParser.Package oldPkg;
4973 PackageSetting oldPkgSetting;
4974 synchronized (mPackages) {
4975 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004976 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4978 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004979 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 return;
4981 }
4982 }
4983 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4984 res.removedInfo.removedPackage = packageName;
4985 // Remove existing system package
4986 removePackageLI(oldPkg, true);
4987 synchronized (mPackages) {
4988 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4989 }
4990
4991 // Successfully disabled the old package. Now proceed with re-installation
4992 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4993 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004994 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004996 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004997 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4998 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4999 }
5000 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005001 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 updatedSettings = true;
5003 }
5004
5005 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5006 //update signature on the new package setting
5007 //this should always succeed, since we checked the
5008 //signature earlier.
5009 synchronized(mPackages) {
5010 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5011 parseFlags, true);
5012 }
5013 } else {
5014 // Re installation failed. Restore old information
5015 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005016 if (newPackage != null) {
5017 removePackageLI(newPackage, true);
5018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005020 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005022 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 // Restore the old system information in Settings
5024 synchronized(mPackages) {
5025 if(updatedSettings) {
5026 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005027 mSettings.setInstallerPackageName(packageName,
5028 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 }
5030 mSettings.writeLP();
5031 }
5032 }
5033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005034
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005035 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005036 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005037 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 synchronized (mPackages) {
5039 //write settings. the installStatus will be incomplete at this stage.
5040 //note that the new package setting would have already been
5041 //added to mPackages. It hasn't been persisted yet.
5042 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5043 mSettings.writeLP();
5044 }
5045
5046 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005047 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5048 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005050 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5052 return;
5053 }
5054 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005055 res.returnCode = setPermissionsLI(newPackage);
5056 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5057 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005059 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 }
5061 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5062 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005063 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 }
5065 }
5066
5067 synchronized (mPackages) {
5068 grantPermissionsLP(newPackage, true);
5069 res.name = pkgName;
5070 res.uid = newPackage.applicationInfo.uid;
5071 res.pkg = newPackage;
5072 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005073 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5075 //to update install status
5076 mSettings.writeLP();
5077 }
5078 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005079
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005080 private void installPackageLI(InstallArgs args,
5081 boolean newInstall, PackageInstalledInfo res) {
5082 int pFlags = args.flags;
5083 String installerPackageName = args.installerPackageName;
5084 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005085 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
5086 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005087 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005088 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5089 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005090 // Result object to be returned
5091 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5092
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005093 // Retrieve PackageSettings and parse package
5094 int parseFlags = PackageParser.PARSE_CHATTY |
5095 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5096 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5097 parseFlags |= mDefParseFlags;
5098 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5099 pp.setSeparateProcesses(mSeparateProcesses);
5100 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5101 null, mMetrics, parseFlags);
5102 if (pkg == null) {
5103 res.returnCode = pp.getParseError();
5104 return;
5105 }
5106 String pkgName = res.name = pkg.packageName;
5107 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5108 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5109 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5110 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005112 }
5113 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5114 res.returnCode = pp.getParseError();
5115 return;
5116 }
5117 // Some preinstall checks
5118 if (forwardLocked && onSd) {
5119 // Make sure forward locked apps can only be installed
5120 // on internal storage
5121 Log.w(TAG, "Cannot install protected apps on sdcard");
5122 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5123 return;
5124 }
5125 // Get rid of all references to package scan path via parser.
5126 pp = null;
5127 String oldCodePath = null;
5128 boolean systemApp = false;
5129 synchronized (mPackages) {
5130 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005131 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5132 String oldName = mSettings.mRenamedPackages.get(pkgName);
5133 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5134 && mPackages.containsKey(oldName)) {
5135 // This package is derived from an original package,
5136 // and this device has been updating from that original
5137 // name. We must continue using the original name, so
5138 // rename the new package here.
5139 pkg.setPackageName(pkg.mOriginalPackage);
5140 pkgName = pkg.packageName;
5141 replace = true;
5142 } else if (mPackages.containsKey(pkgName)) {
5143 // This package, under its official name, already exists
5144 // on the device; we should replace it.
5145 replace = true;
5146 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005147 }
5148 PackageSetting ps = mSettings.mPackages.get(pkgName);
5149 if (ps != null) {
5150 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5151 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5152 systemApp = (ps.pkg.applicationInfo.flags &
5153 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005154 }
5155 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005156 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005157
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005158 if (systemApp && onSd) {
5159 // Disable updates to system apps on sdcard
5160 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5161 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5162 return;
5163 }
5164 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5165 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5166 return;
5167 }
5168 // Set application objects path explicitly after the rename
5169 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005170 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005171 replacePackageLI(pkg, parseFlags, scanMode,
5172 installerPackageName, res);
5173 } else {
5174 installNewPackageLI(pkg, parseFlags, scanMode,
5175 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005176 }
5177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005178
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005179 private int setPermissionsLI(PackageParser.Package newPackage) {
5180 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 int retCode = 0;
5182 // TODO Gross hack but fix later. Ideally move this to be a post installation
5183 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005184 if ((newPackage.applicationInfo.flags
5185 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5186 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 try {
5188 extractPublicFiles(newPackage, destResourceFile);
5189 } catch (IOException e) {
5190 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5191 " forward-locked app.");
5192 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5193 } finally {
5194 //TODO clean up the extracted public files
5195 }
5196 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005197 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 newPackage.applicationInfo.uid);
5199 } else {
5200 final int filePermissions =
5201 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005202 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 newPackage.applicationInfo.uid);
5204 }
5205 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 // The permissions on the resource file was set when it was copied for
5207 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005208 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005210 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005211 Log.e(TAG, "Couldn't set new package file permissions for " +
5212 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005214 // TODO Define new internal error
5215 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 }
5217 return PackageManager.INSTALL_SUCCEEDED;
5218 }
5219
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005220 private boolean isForwardLocked(PackageParser.Package pkg) {
5221 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 }
5223
5224 private void extractPublicFiles(PackageParser.Package newPackage,
5225 File publicZipFile) throws IOException {
5226 final ZipOutputStream publicZipOutStream =
5227 new ZipOutputStream(new FileOutputStream(publicZipFile));
5228 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5229
5230 // Copy manifest, resources.arsc and res directory to public zip
5231
5232 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5233 while (privateZipEntries.hasMoreElements()) {
5234 final ZipEntry zipEntry = privateZipEntries.nextElement();
5235 final String zipEntryName = zipEntry.getName();
5236 if ("AndroidManifest.xml".equals(zipEntryName)
5237 || "resources.arsc".equals(zipEntryName)
5238 || zipEntryName.startsWith("res/")) {
5239 try {
5240 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5241 } catch (IOException e) {
5242 try {
5243 publicZipOutStream.close();
5244 throw e;
5245 } finally {
5246 publicZipFile.delete();
5247 }
5248 }
5249 }
5250 }
5251
5252 publicZipOutStream.close();
5253 FileUtils.setPermissions(
5254 publicZipFile.getAbsolutePath(),
5255 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5256 -1, -1);
5257 }
5258
5259 private static void copyZipEntry(ZipEntry zipEntry,
5260 ZipFile inZipFile,
5261 ZipOutputStream outZipStream) throws IOException {
5262 byte[] buffer = new byte[4096];
5263 int num;
5264
5265 ZipEntry newEntry;
5266 if (zipEntry.getMethod() == ZipEntry.STORED) {
5267 // Preserve the STORED method of the input entry.
5268 newEntry = new ZipEntry(zipEntry);
5269 } else {
5270 // Create a new entry so that the compressed len is recomputed.
5271 newEntry = new ZipEntry(zipEntry.getName());
5272 }
5273 outZipStream.putNextEntry(newEntry);
5274
5275 InputStream data = inZipFile.getInputStream(zipEntry);
5276 while ((num = data.read(buffer)) > 0) {
5277 outZipStream.write(buffer, 0, num);
5278 }
5279 outZipStream.flush();
5280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 private void deleteTempPackageFiles() {
5283 FilenameFilter filter = new FilenameFilter() {
5284 public boolean accept(File dir, String name) {
5285 return name.startsWith("vmdl") && name.endsWith(".tmp");
5286 }
5287 };
5288 String tmpFilesList[] = mAppInstallDir.list(filter);
5289 if(tmpFilesList == null) {
5290 return;
5291 }
5292 for(int i = 0; i < tmpFilesList.length; i++) {
5293 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5294 tmpFile.delete();
5295 }
5296 }
5297
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005298 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 File tmpPackageFile;
5300 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005301 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005302 } catch (IOException e) {
5303 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5304 return null;
5305 }
5306 try {
5307 FileUtils.setPermissions(
5308 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5309 -1, -1);
5310 } catch (IOException e) {
5311 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5312 return null;
5313 }
5314 return tmpPackageFile;
5315 }
5316
5317 public void deletePackage(final String packageName,
5318 final IPackageDeleteObserver observer,
5319 final int flags) {
5320 mContext.enforceCallingOrSelfPermission(
5321 android.Manifest.permission.DELETE_PACKAGES, null);
5322 // Queue up an async operation since the package deletion may take a little while.
5323 mHandler.post(new Runnable() {
5324 public void run() {
5325 mHandler.removeCallbacks(this);
5326 final boolean succeded = deletePackageX(packageName, true, true, flags);
5327 if (observer != null) {
5328 try {
5329 observer.packageDeleted(succeded);
5330 } catch (RemoteException e) {
5331 Log.i(TAG, "Observer no longer exists.");
5332 } //end catch
5333 } //end if
5334 } //end run
5335 });
5336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 /**
5339 * This method is an internal method that could be get invoked either
5340 * to delete an installed package or to clean up a failed installation.
5341 * After deleting an installed package, a broadcast is sent to notify any
5342 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005343 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 * installation wouldn't have sent the initial broadcast either
5345 * The key steps in deleting a package are
5346 * deleting the package information in internal structures like mPackages,
5347 * deleting the packages base directories through installd
5348 * updating mSettings to reflect current status
5349 * persisting settings for later use
5350 * sending a broadcast if necessary
5351 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5353 boolean deleteCodeAndResources, int flags) {
5354 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005355 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356
5357 synchronized (mInstallLock) {
5358 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005362 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5363 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5364
5365 // If the removed package was a system update, the old system packaged
5366 // was re-enabled; we need to broadcast this information
5367 if (systemUpdate) {
5368 Bundle extras = new Bundle(1);
5369 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5370 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5371
5372 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5373 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005375 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005376 // Delete the resources here after sending the broadcast to let
5377 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005378 if (info.args != null) {
5379 synchronized (mInstallLock) {
5380 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005381 }
5382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 return res;
5384 }
5385
5386 static class PackageRemovedInfo {
5387 String removedPackage;
5388 int uid = -1;
5389 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005390 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005391 // Clean up resources deleted packages.
5392 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 void sendBroadcast(boolean fullRemove, boolean replacing) {
5395 Bundle extras = new Bundle(1);
5396 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5397 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5398 if (replacing) {
5399 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5400 }
5401 if (removedPackage != null) {
5402 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5403 }
5404 if (removedUid >= 0) {
5405 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5406 }
5407 }
5408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 /*
5411 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5412 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005413 * 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 -08005414 * delete a partially installed application.
5415 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005416 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 int flags) {
5418 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005419 if (outInfo != null) {
5420 outInfo.removedPackage = packageName;
5421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 removePackageLI(p, true);
5423 // Retrieve object to delete permissions for shared user later on
5424 PackageSetting deletedPs;
5425 synchronized (mPackages) {
5426 deletedPs = mSettings.mPackages.get(packageName);
5427 }
5428 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005429 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005431 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 if (retCode < 0) {
5433 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5434 + packageName + ", retcode=" + retCode);
5435 // we don't consider this to be a failure of the core package deletion
5436 }
5437 } else {
5438 //for emulator
5439 PackageParser.Package pkg = mPackages.get(packageName);
5440 File dataDir = new File(pkg.applicationInfo.dataDir);
5441 dataDir.delete();
5442 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005443 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005445 if (outInfo != null) {
5446 outInfo.removedUid = mSettings.removePackageLP(packageName);
5447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 }
5449 }
5450 synchronized (mPackages) {
5451 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5452 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005453 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 }
5455 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005456 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 }
5458 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 /*
5461 * Tries to delete system package.
5462 */
5463 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005464 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 ApplicationInfo applicationInfo = p.applicationInfo;
5466 //applicable for non-partially installed applications only
5467 if (applicationInfo == null) {
5468 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5469 return false;
5470 }
5471 PackageSetting ps = null;
5472 // Confirm if the system package has been updated
5473 // An updated system app can be deleted. This will also have to restore
5474 // the system pkg from system partition
5475 synchronized (mPackages) {
5476 ps = mSettings.getDisabledSystemPkg(p.packageName);
5477 }
5478 if (ps == null) {
5479 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5480 return false;
5481 } else {
5482 Log.i(TAG, "Deleting system pkg from data partition");
5483 }
5484 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005485 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005486 boolean deleteCodeAndResources = false;
5487 if (ps.versionCode < p.mVersionCode) {
5488 // Delete code and resources for downgrades
5489 deleteCodeAndResources = true;
5490 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5491 flags &= ~PackageManager.DONT_DELETE_DATA;
5492 }
5493 } else {
5494 // Preserve data by setting flag
5495 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5496 flags |= PackageManager.DONT_DELETE_DATA;
5497 }
5498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5500 if (!ret) {
5501 return false;
5502 }
5503 synchronized (mPackages) {
5504 // Reinstate the old system package
5505 mSettings.enableSystemPackageLP(p.packageName);
5506 }
5507 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005508 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005510 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 if (newPkg == null) {
5513 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5514 return false;
5515 }
5516 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005517 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 mSettings.writeLP();
5519 }
5520 return true;
5521 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5524 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5525 ApplicationInfo applicationInfo = p.applicationInfo;
5526 if (applicationInfo == null) {
5527 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5528 return false;
5529 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005530 if (outInfo != null) {
5531 outInfo.uid = applicationInfo.uid;
5532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533
5534 // Delete package data from internal structures and also remove data if flag is set
5535 removePackageDataLI(p, outInfo, flags);
5536
5537 // Delete application code and resources
5538 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005539 // TODO can pick up from PackageSettings as well
5540 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5541 PackageManager.INSTALL_ON_SDCARD : 0;
5542 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5543 PackageManager.INSTALL_FORWARD_LOCK : 0;
5544 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005545 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 }
5547 return true;
5548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 /*
5551 * This method handles package deletion in general
5552 */
5553 private boolean deletePackageLI(String packageName,
5554 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5555 if (packageName == null) {
5556 Log.w(TAG, "Attempt to delete null packageName.");
5557 return false;
5558 }
5559 PackageParser.Package p;
5560 boolean dataOnly = false;
5561 synchronized (mPackages) {
5562 p = mPackages.get(packageName);
5563 if (p == null) {
5564 //this retrieves partially installed apps
5565 dataOnly = true;
5566 PackageSetting ps = mSettings.mPackages.get(packageName);
5567 if (ps == null) {
5568 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5569 return false;
5570 }
5571 p = ps.pkg;
5572 }
5573 }
5574 if (p == null) {
5575 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5576 return false;
5577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 if (dataOnly) {
5580 // Delete application data first
5581 removePackageDataLI(p, outInfo, flags);
5582 return true;
5583 }
5584 // At this point the package should have ApplicationInfo associated with it
5585 if (p.applicationInfo == null) {
5586 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5587 return false;
5588 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005589 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5591 Log.i(TAG, "Removing system package:"+p.packageName);
5592 // When an updated system application is deleted we delete the existing resources as well and
5593 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005594 ret = deleteSystemPackageLI(p, flags, outInfo);
5595 } else {
5596 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005597 // Kill application pre-emptively especially for apps on sd.
5598 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005599 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005601 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 public void clearApplicationUserData(final String packageName,
5605 final IPackageDataObserver observer) {
5606 mContext.enforceCallingOrSelfPermission(
5607 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5608 // Queue up an async operation since the package deletion may take a little while.
5609 mHandler.post(new Runnable() {
5610 public void run() {
5611 mHandler.removeCallbacks(this);
5612 final boolean succeeded;
5613 synchronized (mInstallLock) {
5614 succeeded = clearApplicationUserDataLI(packageName);
5615 }
5616 if (succeeded) {
5617 // invoke DeviceStorageMonitor's update method to clear any notifications
5618 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5619 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5620 if (dsm != null) {
5621 dsm.updateMemory();
5622 }
5623 }
5624 if(observer != null) {
5625 try {
5626 observer.onRemoveCompleted(packageName, succeeded);
5627 } catch (RemoteException e) {
5628 Log.i(TAG, "Observer no longer exists.");
5629 }
5630 } //end if observer
5631 } //end run
5632 });
5633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 private boolean clearApplicationUserDataLI(String packageName) {
5636 if (packageName == null) {
5637 Log.w(TAG, "Attempt to delete null packageName.");
5638 return false;
5639 }
5640 PackageParser.Package p;
5641 boolean dataOnly = false;
5642 synchronized (mPackages) {
5643 p = mPackages.get(packageName);
5644 if(p == null) {
5645 dataOnly = true;
5646 PackageSetting ps = mSettings.mPackages.get(packageName);
5647 if((ps == null) || (ps.pkg == null)) {
5648 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5649 return false;
5650 }
5651 p = ps.pkg;
5652 }
5653 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005654 boolean useEncryptedFSDir = false;
5655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 if(!dataOnly) {
5657 //need to check this only for fully installed applications
5658 if (p == null) {
5659 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5660 return false;
5661 }
5662 final ApplicationInfo applicationInfo = p.applicationInfo;
5663 if (applicationInfo == null) {
5664 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5665 return false;
5666 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005667 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 }
5669 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005670 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 if (retCode < 0) {
5672 Log.w(TAG, "Couldn't remove cache files for package: "
5673 + packageName);
5674 return false;
5675 }
5676 }
5677 return true;
5678 }
5679
5680 public void deleteApplicationCacheFiles(final String packageName,
5681 final IPackageDataObserver observer) {
5682 mContext.enforceCallingOrSelfPermission(
5683 android.Manifest.permission.DELETE_CACHE_FILES, null);
5684 // Queue up an async operation since the package deletion may take a little while.
5685 mHandler.post(new Runnable() {
5686 public void run() {
5687 mHandler.removeCallbacks(this);
5688 final boolean succeded;
5689 synchronized (mInstallLock) {
5690 succeded = deleteApplicationCacheFilesLI(packageName);
5691 }
5692 if(observer != null) {
5693 try {
5694 observer.onRemoveCompleted(packageName, succeded);
5695 } catch (RemoteException e) {
5696 Log.i(TAG, "Observer no longer exists.");
5697 }
5698 } //end if observer
5699 } //end run
5700 });
5701 }
5702
5703 private boolean deleteApplicationCacheFilesLI(String packageName) {
5704 if (packageName == null) {
5705 Log.w(TAG, "Attempt to delete null packageName.");
5706 return false;
5707 }
5708 PackageParser.Package p;
5709 synchronized (mPackages) {
5710 p = mPackages.get(packageName);
5711 }
5712 if (p == null) {
5713 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5714 return false;
5715 }
5716 final ApplicationInfo applicationInfo = p.applicationInfo;
5717 if (applicationInfo == null) {
5718 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5719 return false;
5720 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005721 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005723 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 if (retCode < 0) {
5725 Log.w(TAG, "Couldn't remove cache files for package: "
5726 + packageName);
5727 return false;
5728 }
5729 }
5730 return true;
5731 }
5732
5733 public void getPackageSizeInfo(final String packageName,
5734 final IPackageStatsObserver observer) {
5735 mContext.enforceCallingOrSelfPermission(
5736 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5737 // Queue up an async operation since the package deletion may take a little while.
5738 mHandler.post(new Runnable() {
5739 public void run() {
5740 mHandler.removeCallbacks(this);
5741 PackageStats lStats = new PackageStats(packageName);
5742 final boolean succeded;
5743 synchronized (mInstallLock) {
5744 succeded = getPackageSizeInfoLI(packageName, lStats);
5745 }
5746 if(observer != null) {
5747 try {
5748 observer.onGetStatsCompleted(lStats, succeded);
5749 } catch (RemoteException e) {
5750 Log.i(TAG, "Observer no longer exists.");
5751 }
5752 } //end if observer
5753 } //end run
5754 });
5755 }
5756
5757 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5758 if (packageName == null) {
5759 Log.w(TAG, "Attempt to get size of null packageName.");
5760 return false;
5761 }
5762 PackageParser.Package p;
5763 boolean dataOnly = false;
5764 synchronized (mPackages) {
5765 p = mPackages.get(packageName);
5766 if(p == null) {
5767 dataOnly = true;
5768 PackageSetting ps = mSettings.mPackages.get(packageName);
5769 if((ps == null) || (ps.pkg == null)) {
5770 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5771 return false;
5772 }
5773 p = ps.pkg;
5774 }
5775 }
5776 String publicSrcDir = null;
5777 if(!dataOnly) {
5778 final ApplicationInfo applicationInfo = p.applicationInfo;
5779 if (applicationInfo == null) {
5780 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5781 return false;
5782 }
5783 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5784 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005785 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 if (mInstaller != null) {
5787 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005788 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 if (res < 0) {
5790 return false;
5791 } else {
5792 return true;
5793 }
5794 }
5795 return true;
5796 }
5797
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 public void addPackageToPreferred(String packageName) {
5800 mContext.enforceCallingOrSelfPermission(
5801 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005802 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 }
5804
5805 public void removePackageFromPreferred(String packageName) {
5806 mContext.enforceCallingOrSelfPermission(
5807 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005808 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 }
5810
5811 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005812 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 }
5814
5815 public void addPreferredActivity(IntentFilter filter, int match,
5816 ComponentName[] set, ComponentName activity) {
5817 mContext.enforceCallingOrSelfPermission(
5818 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5819
5820 synchronized (mPackages) {
5821 Log.i(TAG, "Adding preferred activity " + activity + ":");
5822 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5823 mSettings.mPreferredActivities.addFilter(
5824 new PreferredActivity(filter, match, set, activity));
5825 mSettings.writeLP();
5826 }
5827 }
5828
Satish Sampath8dbe6122009-06-02 23:35:54 +01005829 public void replacePreferredActivity(IntentFilter filter, int match,
5830 ComponentName[] set, ComponentName activity) {
5831 mContext.enforceCallingOrSelfPermission(
5832 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5833 if (filter.countActions() != 1) {
5834 throw new IllegalArgumentException(
5835 "replacePreferredActivity expects filter to have only 1 action.");
5836 }
5837 if (filter.countCategories() != 1) {
5838 throw new IllegalArgumentException(
5839 "replacePreferredActivity expects filter to have only 1 category.");
5840 }
5841 if (filter.countDataAuthorities() != 0
5842 || filter.countDataPaths() != 0
5843 || filter.countDataSchemes() != 0
5844 || filter.countDataTypes() != 0) {
5845 throw new IllegalArgumentException(
5846 "replacePreferredActivity expects filter to have no data authorities, " +
5847 "paths, schemes or types.");
5848 }
5849 synchronized (mPackages) {
5850 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5851 String action = filter.getAction(0);
5852 String category = filter.getCategory(0);
5853 while (it.hasNext()) {
5854 PreferredActivity pa = it.next();
5855 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5856 it.remove();
5857 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5858 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5859 }
5860 }
5861 addPreferredActivity(filter, match, set, activity);
5862 }
5863 }
5864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 public void clearPackagePreferredActivities(String packageName) {
5866 mContext.enforceCallingOrSelfPermission(
5867 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5868
5869 synchronized (mPackages) {
5870 if (clearPackagePreferredActivitiesLP(packageName)) {
5871 mSettings.writeLP();
5872 }
5873 }
5874 }
5875
5876 boolean clearPackagePreferredActivitiesLP(String packageName) {
5877 boolean changed = false;
5878 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5879 while (it.hasNext()) {
5880 PreferredActivity pa = it.next();
5881 if (pa.mActivity.getPackageName().equals(packageName)) {
5882 it.remove();
5883 changed = true;
5884 }
5885 }
5886 return changed;
5887 }
5888
5889 public int getPreferredActivities(List<IntentFilter> outFilters,
5890 List<ComponentName> outActivities, String packageName) {
5891
5892 int num = 0;
5893 synchronized (mPackages) {
5894 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5895 while (it.hasNext()) {
5896 PreferredActivity pa = it.next();
5897 if (packageName == null
5898 || pa.mActivity.getPackageName().equals(packageName)) {
5899 if (outFilters != null) {
5900 outFilters.add(new IntentFilter(pa));
5901 }
5902 if (outActivities != null) {
5903 outActivities.add(pa.mActivity);
5904 }
5905 }
5906 }
5907 }
5908
5909 return num;
5910 }
5911
5912 public void setApplicationEnabledSetting(String appPackageName,
5913 int newState, int flags) {
5914 setEnabledSetting(appPackageName, null, newState, flags);
5915 }
5916
5917 public void setComponentEnabledSetting(ComponentName componentName,
5918 int newState, int flags) {
5919 setEnabledSetting(componentName.getPackageName(),
5920 componentName.getClassName(), newState, flags);
5921 }
5922
5923 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005924 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5926 || newState == COMPONENT_ENABLED_STATE_ENABLED
5927 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5928 throw new IllegalArgumentException("Invalid new component state: "
5929 + newState);
5930 }
5931 PackageSetting pkgSetting;
5932 final int uid = Binder.getCallingUid();
5933 final int permission = mContext.checkCallingPermission(
5934 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5935 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005936 boolean sendNow = false;
5937 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005938 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005940 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005942 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005944 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005946 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 }
5948 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005949 "Unknown component: " + packageName
5950 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 }
5952 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5953 throw new SecurityException(
5954 "Permission Denial: attempt to change component state from pid="
5955 + Binder.getCallingPid()
5956 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5957 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005958 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 // We're dealing with an application/package level state change
5960 pkgSetting.enabled = newState;
5961 } else {
5962 // We're dealing with a component level state change
5963 switch (newState) {
5964 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005965 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 break;
5967 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005968 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 break;
5970 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005971 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 break;
5973 default:
5974 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005975 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
5977 }
5978 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005979 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005980 components = mPendingBroadcasts.get(packageName);
5981 boolean newPackage = components == null;
5982 if (newPackage) {
5983 components = new ArrayList<String>();
5984 }
5985 if (!components.contains(componentName)) {
5986 components.add(componentName);
5987 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005988 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5989 sendNow = true;
5990 // Purge entry from pending broadcast list if another one exists already
5991 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005992 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005993 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005994 if (newPackage) {
5995 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005996 }
5997 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5998 // Schedule a message
5999 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6000 }
6001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 long callingId = Binder.clearCallingIdentity();
6005 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006006 if (sendNow) {
6007 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006008 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 } finally {
6011 Binder.restoreCallingIdentity(callingId);
6012 }
6013 }
6014
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006015 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006016 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6017 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6018 + " components=" + componentNames);
6019 Bundle extras = new Bundle(4);
6020 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6021 String nameList[] = new String[componentNames.size()];
6022 componentNames.toArray(nameList);
6023 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006024 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6025 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006026 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006027 }
6028
Jacek Surazski65e13172009-04-28 15:26:38 +02006029 public String getInstallerPackageName(String packageName) {
6030 synchronized (mPackages) {
6031 PackageSetting pkg = mSettings.mPackages.get(packageName);
6032 if (pkg == null) {
6033 throw new IllegalArgumentException("Unknown package: " + packageName);
6034 }
6035 return pkg.installerPackageName;
6036 }
6037 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 public int getApplicationEnabledSetting(String appPackageName) {
6040 synchronized (mPackages) {
6041 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6042 if (pkg == null) {
6043 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6044 }
6045 return pkg.enabled;
6046 }
6047 }
6048
6049 public int getComponentEnabledSetting(ComponentName componentName) {
6050 synchronized (mPackages) {
6051 final String packageNameStr = componentName.getPackageName();
6052 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6053 if (pkg == null) {
6054 throw new IllegalArgumentException("Unknown component: " + componentName);
6055 }
6056 final String classNameStr = componentName.getClassName();
6057 return pkg.currentEnabledStateLP(classNameStr);
6058 }
6059 }
6060
6061 public void enterSafeMode() {
6062 if (!mSystemReady) {
6063 mSafeMode = true;
6064 }
6065 }
6066
6067 public void systemReady() {
6068 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006069
6070 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006071 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006072 mContext.getContentResolver(),
6073 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006074 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006075 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006076 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 }
6079
6080 public boolean isSafeMode() {
6081 return mSafeMode;
6082 }
6083
6084 public boolean hasSystemUidErrors() {
6085 return mHasSystemUidErrors;
6086 }
6087
6088 static String arrayToString(int[] array) {
6089 StringBuffer buf = new StringBuffer(128);
6090 buf.append('[');
6091 if (array != null) {
6092 for (int i=0; i<array.length; i++) {
6093 if (i > 0) buf.append(", ");
6094 buf.append(array[i]);
6095 }
6096 }
6097 buf.append(']');
6098 return buf.toString();
6099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 @Override
6102 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6103 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6104 != PackageManager.PERMISSION_GRANTED) {
6105 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6106 + Binder.getCallingPid()
6107 + ", uid=" + Binder.getCallingUid()
6108 + " without permission "
6109 + android.Manifest.permission.DUMP);
6110 return;
6111 }
6112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 synchronized (mPackages) {
6114 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006115 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 pw.println(" ");
6117 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006118 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 pw.println(" ");
6120 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006121 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 pw.println(" ");
6123 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006124 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 pw.println("Permissions:");
6127 {
6128 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006129 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6130 pw.print(Integer.toHexString(System.identityHashCode(p)));
6131 pw.println("):");
6132 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6133 pw.print(" uid="); pw.print(p.uid);
6134 pw.print(" gids="); pw.print(arrayToString(p.gids));
6135 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 }
6137 }
6138 pw.println(" ");
6139 pw.println("Packages:");
6140 {
6141 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006142 pw.print(" Package [");
6143 pw.print(ps.realName != null ? ps.realName : ps.name);
6144 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006145 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6146 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006147 if (ps.realName != null) {
6148 pw.print(" compat name="); pw.println(ps.name);
6149 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006150 pw.print(" userId="); pw.print(ps.userId);
6151 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6152 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6153 pw.print(" pkg="); pw.println(ps.pkg);
6154 pw.print(" codePath="); pw.println(ps.codePathString);
6155 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006157 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006158 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006159 pw.print(" supportsScreens=[");
6160 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006161 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006162 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006163 if (!first) pw.print(", ");
6164 first = false;
6165 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006166 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006167 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006168 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006169 if (!first) pw.print(", ");
6170 first = false;
6171 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006173 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006174 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006175 if (!first) pw.print(", ");
6176 first = false;
6177 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006178 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006179 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006180 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006181 if (!first) pw.print(", ");
6182 first = false;
6183 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006184 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006185 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006186 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6187 if (!first) pw.print(", ");
6188 first = false;
6189 pw.print("anyDensity");
6190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006192 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006193 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6194 pw.print(" signatures="); pw.println(ps.signatures);
6195 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6196 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6197 pw.print(" installStatus="); pw.print(ps.installStatus);
6198 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 if (ps.disabledComponents.size() > 0) {
6200 pw.println(" disabledComponents:");
6201 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006202 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 }
6204 }
6205 if (ps.enabledComponents.size() > 0) {
6206 pw.println(" enabledComponents:");
6207 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006208 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 }
6210 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006211 if (ps.grantedPermissions.size() > 0) {
6212 pw.println(" grantedPermissions:");
6213 for (String s : ps.grantedPermissions) {
6214 pw.print(" "); pw.println(s);
6215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006217 if (ps.loadedPermissions.size() > 0) {
6218 pw.println(" loadedPermissions:");
6219 for (String s : ps.loadedPermissions) {
6220 pw.print(" "); pw.println(s);
6221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 }
6223 }
6224 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006225 if (mSettings.mRenamedPackages.size() > 0) {
6226 pw.println(" ");
6227 pw.println("Renamed packages:");
6228 for (HashMap.Entry<String, String> e
6229 : mSettings.mRenamedPackages.entrySet()) {
6230 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6231 pw.println(e.getValue());
6232 }
6233 }
6234 if (mSettings.mDisabledSysPackages.size() > 0) {
6235 pw.println(" ");
6236 pw.println("Hidden system packages:");
6237 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6238 pw.print(" Package [");
6239 pw.print(ps.realName != null ? ps.realName : ps.name);
6240 pw.print("] (");
6241 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6242 pw.println("):");
6243 if (ps.realName != null) {
6244 pw.print(" compat name="); pw.println(ps.name);
6245 }
6246 pw.print(" userId="); pw.println(ps.userId);
6247 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6248 pw.print(" codePath="); pw.println(ps.codePathString);
6249 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6250 }
6251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 pw.println(" ");
6253 pw.println("Shared Users:");
6254 {
6255 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006256 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6257 pw.print(Integer.toHexString(System.identityHashCode(su)));
6258 pw.println("):");
6259 pw.print(" userId="); pw.print(su.userId);
6260 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 pw.println(" grantedPermissions:");
6262 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006263 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 }
6265 pw.println(" loadedPermissions:");
6266 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006267 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 }
6269 }
6270 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 pw.println(" ");
6273 pw.println("Settings parse messages:");
6274 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006275
6276 pw.println(" ");
6277 pw.println("Package warning messages:");
6278 File fname = getSettingsProblemFile();
6279 FileInputStream in;
6280 try {
6281 in = new FileInputStream(fname);
6282 int avail = in.available();
6283 byte[] data = new byte[avail];
6284 in.read(data);
6285 pw.println(new String(data));
6286 } catch (FileNotFoundException e) {
6287 } catch (IOException e) {
6288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006290
6291 synchronized (mProviders) {
6292 pw.println(" ");
6293 pw.println("Registered ContentProviders:");
6294 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006295 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006296 pw.println(p.toString());
6297 }
6298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 }
6300
6301 static final class BasePermission {
6302 final static int TYPE_NORMAL = 0;
6303 final static int TYPE_BUILTIN = 1;
6304 final static int TYPE_DYNAMIC = 2;
6305
6306 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006307 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 final int type;
6309 PackageParser.Permission perm;
6310 PermissionInfo pendingInfo;
6311 int uid;
6312 int[] gids;
6313
6314 BasePermission(String _name, String _sourcePackage, int _type) {
6315 name = _name;
6316 sourcePackage = _sourcePackage;
6317 type = _type;
6318 }
6319 }
6320
6321 static class PackageSignatures {
6322 private Signature[] mSignatures;
6323
6324 PackageSignatures(Signature[] sigs) {
6325 assignSignatures(sigs);
6326 }
6327
6328 PackageSignatures() {
6329 }
6330
6331 void writeXml(XmlSerializer serializer, String tagName,
6332 ArrayList<Signature> pastSignatures) throws IOException {
6333 if (mSignatures == null) {
6334 return;
6335 }
6336 serializer.startTag(null, tagName);
6337 serializer.attribute(null, "count",
6338 Integer.toString(mSignatures.length));
6339 for (int i=0; i<mSignatures.length; i++) {
6340 serializer.startTag(null, "cert");
6341 final Signature sig = mSignatures[i];
6342 final int sigHash = sig.hashCode();
6343 final int numPast = pastSignatures.size();
6344 int j;
6345 for (j=0; j<numPast; j++) {
6346 Signature pastSig = pastSignatures.get(j);
6347 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6348 serializer.attribute(null, "index", Integer.toString(j));
6349 break;
6350 }
6351 }
6352 if (j >= numPast) {
6353 pastSignatures.add(sig);
6354 serializer.attribute(null, "index", Integer.toString(numPast));
6355 serializer.attribute(null, "key", sig.toCharsString());
6356 }
6357 serializer.endTag(null, "cert");
6358 }
6359 serializer.endTag(null, tagName);
6360 }
6361
6362 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6363 throws IOException, XmlPullParserException {
6364 String countStr = parser.getAttributeValue(null, "count");
6365 if (countStr == null) {
6366 reportSettingsProblem(Log.WARN,
6367 "Error in package manager settings: <signatures> has"
6368 + " no count at " + parser.getPositionDescription());
6369 XmlUtils.skipCurrentTag(parser);
6370 }
6371 final int count = Integer.parseInt(countStr);
6372 mSignatures = new Signature[count];
6373 int pos = 0;
6374
6375 int outerDepth = parser.getDepth();
6376 int type;
6377 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6378 && (type != XmlPullParser.END_TAG
6379 || parser.getDepth() > outerDepth)) {
6380 if (type == XmlPullParser.END_TAG
6381 || type == XmlPullParser.TEXT) {
6382 continue;
6383 }
6384
6385 String tagName = parser.getName();
6386 if (tagName.equals("cert")) {
6387 if (pos < count) {
6388 String index = parser.getAttributeValue(null, "index");
6389 if (index != null) {
6390 try {
6391 int idx = Integer.parseInt(index);
6392 String key = parser.getAttributeValue(null, "key");
6393 if (key == null) {
6394 if (idx >= 0 && idx < pastSignatures.size()) {
6395 Signature sig = pastSignatures.get(idx);
6396 if (sig != null) {
6397 mSignatures[pos] = pastSignatures.get(idx);
6398 pos++;
6399 } else {
6400 reportSettingsProblem(Log.WARN,
6401 "Error in package manager settings: <cert> "
6402 + "index " + index + " is not defined at "
6403 + parser.getPositionDescription());
6404 }
6405 } else {
6406 reportSettingsProblem(Log.WARN,
6407 "Error in package manager settings: <cert> "
6408 + "index " + index + " is out of bounds at "
6409 + parser.getPositionDescription());
6410 }
6411 } else {
6412 while (pastSignatures.size() <= idx) {
6413 pastSignatures.add(null);
6414 }
6415 Signature sig = new Signature(key);
6416 pastSignatures.set(idx, sig);
6417 mSignatures[pos] = sig;
6418 pos++;
6419 }
6420 } catch (NumberFormatException e) {
6421 reportSettingsProblem(Log.WARN,
6422 "Error in package manager settings: <cert> "
6423 + "index " + index + " is not a number at "
6424 + parser.getPositionDescription());
6425 }
6426 } else {
6427 reportSettingsProblem(Log.WARN,
6428 "Error in package manager settings: <cert> has"
6429 + " no index at " + parser.getPositionDescription());
6430 }
6431 } else {
6432 reportSettingsProblem(Log.WARN,
6433 "Error in package manager settings: too "
6434 + "many <cert> tags, expected " + count
6435 + " at " + parser.getPositionDescription());
6436 }
6437 } else {
6438 reportSettingsProblem(Log.WARN,
6439 "Unknown element under <cert>: "
6440 + parser.getName());
6441 }
6442 XmlUtils.skipCurrentTag(parser);
6443 }
6444
6445 if (pos < count) {
6446 // Should never happen -- there is an error in the written
6447 // settings -- but if it does we don't want to generate
6448 // a bad array.
6449 Signature[] newSigs = new Signature[pos];
6450 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6451 mSignatures = newSigs;
6452 }
6453 }
6454
6455 /**
6456 * If any of the given 'sigs' is contained in the existing signatures,
6457 * then completely replace the current signatures with the ones in
6458 * 'sigs'. This is used for updating an existing package to a newly
6459 * installed version.
6460 */
6461 boolean updateSignatures(Signature[] sigs, boolean update) {
6462 if (mSignatures == null) {
6463 if (update) {
6464 assignSignatures(sigs);
6465 }
6466 return true;
6467 }
6468 if (sigs == null) {
6469 return false;
6470 }
6471
6472 for (int i=0; i<sigs.length; i++) {
6473 Signature sig = sigs[i];
6474 for (int j=0; j<mSignatures.length; j++) {
6475 if (mSignatures[j].equals(sig)) {
6476 if (update) {
6477 assignSignatures(sigs);
6478 }
6479 return true;
6480 }
6481 }
6482 }
6483 return false;
6484 }
6485
6486 /**
6487 * If any of the given 'sigs' is contained in the existing signatures,
6488 * then add in any new signatures found in 'sigs'. This is used for
6489 * including a new package into an existing shared user id.
6490 */
6491 boolean mergeSignatures(Signature[] sigs, boolean update) {
6492 if (mSignatures == null) {
6493 if (update) {
6494 assignSignatures(sigs);
6495 }
6496 return true;
6497 }
6498 if (sigs == null) {
6499 return false;
6500 }
6501
6502 Signature[] added = null;
6503 int addedCount = 0;
6504 boolean haveMatch = false;
6505 for (int i=0; i<sigs.length; i++) {
6506 Signature sig = sigs[i];
6507 boolean found = false;
6508 for (int j=0; j<mSignatures.length; j++) {
6509 if (mSignatures[j].equals(sig)) {
6510 found = true;
6511 haveMatch = true;
6512 break;
6513 }
6514 }
6515
6516 if (!found) {
6517 if (added == null) {
6518 added = new Signature[sigs.length];
6519 }
6520 added[i] = sig;
6521 addedCount++;
6522 }
6523 }
6524
6525 if (!haveMatch) {
6526 // Nothing matched -- reject the new signatures.
6527 return false;
6528 }
6529 if (added == null) {
6530 // Completely matched -- nothing else to do.
6531 return true;
6532 }
6533
6534 // Add additional signatures in.
6535 if (update) {
6536 Signature[] total = new Signature[addedCount+mSignatures.length];
6537 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6538 int j = mSignatures.length;
6539 for (int i=0; i<added.length; i++) {
6540 if (added[i] != null) {
6541 total[j] = added[i];
6542 j++;
6543 }
6544 }
6545 mSignatures = total;
6546 }
6547 return true;
6548 }
6549
6550 private void assignSignatures(Signature[] sigs) {
6551 if (sigs == null) {
6552 mSignatures = null;
6553 return;
6554 }
6555 mSignatures = new Signature[sigs.length];
6556 for (int i=0; i<sigs.length; i++) {
6557 mSignatures[i] = sigs[i];
6558 }
6559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 @Override
6562 public String toString() {
6563 StringBuffer buf = new StringBuffer(128);
6564 buf.append("PackageSignatures{");
6565 buf.append(Integer.toHexString(System.identityHashCode(this)));
6566 buf.append(" [");
6567 if (mSignatures != null) {
6568 for (int i=0; i<mSignatures.length; i++) {
6569 if (i > 0) buf.append(", ");
6570 buf.append(Integer.toHexString(
6571 System.identityHashCode(mSignatures[i])));
6572 }
6573 }
6574 buf.append("]}");
6575 return buf.toString();
6576 }
6577 }
6578
6579 static class PreferredActivity extends IntentFilter {
6580 final int mMatch;
6581 final String[] mSetPackages;
6582 final String[] mSetClasses;
6583 final String[] mSetComponents;
6584 final ComponentName mActivity;
6585 final String mShortActivity;
6586 String mParseError;
6587
6588 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6589 ComponentName activity) {
6590 super(filter);
6591 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6592 mActivity = activity;
6593 mShortActivity = activity.flattenToShortString();
6594 mParseError = null;
6595 if (set != null) {
6596 final int N = set.length;
6597 String[] myPackages = new String[N];
6598 String[] myClasses = new String[N];
6599 String[] myComponents = new String[N];
6600 for (int i=0; i<N; i++) {
6601 ComponentName cn = set[i];
6602 if (cn == null) {
6603 mSetPackages = null;
6604 mSetClasses = null;
6605 mSetComponents = null;
6606 return;
6607 }
6608 myPackages[i] = cn.getPackageName().intern();
6609 myClasses[i] = cn.getClassName().intern();
6610 myComponents[i] = cn.flattenToShortString().intern();
6611 }
6612 mSetPackages = myPackages;
6613 mSetClasses = myClasses;
6614 mSetComponents = myComponents;
6615 } else {
6616 mSetPackages = null;
6617 mSetClasses = null;
6618 mSetComponents = null;
6619 }
6620 }
6621
6622 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6623 IOException {
6624 mShortActivity = parser.getAttributeValue(null, "name");
6625 mActivity = ComponentName.unflattenFromString(mShortActivity);
6626 if (mActivity == null) {
6627 mParseError = "Bad activity name " + mShortActivity;
6628 }
6629 String matchStr = parser.getAttributeValue(null, "match");
6630 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6631 String setCountStr = parser.getAttributeValue(null, "set");
6632 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6633
6634 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6635 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6636 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6637
6638 int setPos = 0;
6639
6640 int outerDepth = parser.getDepth();
6641 int type;
6642 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6643 && (type != XmlPullParser.END_TAG
6644 || parser.getDepth() > outerDepth)) {
6645 if (type == XmlPullParser.END_TAG
6646 || type == XmlPullParser.TEXT) {
6647 continue;
6648 }
6649
6650 String tagName = parser.getName();
6651 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6652 // + parser.getDepth() + " tag=" + tagName);
6653 if (tagName.equals("set")) {
6654 String name = parser.getAttributeValue(null, "name");
6655 if (name == null) {
6656 if (mParseError == null) {
6657 mParseError = "No name in set tag in preferred activity "
6658 + mShortActivity;
6659 }
6660 } else if (setPos >= setCount) {
6661 if (mParseError == null) {
6662 mParseError = "Too many set tags in preferred activity "
6663 + mShortActivity;
6664 }
6665 } else {
6666 ComponentName cn = ComponentName.unflattenFromString(name);
6667 if (cn == null) {
6668 if (mParseError == null) {
6669 mParseError = "Bad set name " + name + " in preferred activity "
6670 + mShortActivity;
6671 }
6672 } else {
6673 myPackages[setPos] = cn.getPackageName();
6674 myClasses[setPos] = cn.getClassName();
6675 myComponents[setPos] = name;
6676 setPos++;
6677 }
6678 }
6679 XmlUtils.skipCurrentTag(parser);
6680 } else if (tagName.equals("filter")) {
6681 //Log.i(TAG, "Starting to parse filter...");
6682 readFromXml(parser);
6683 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6684 // + parser.getDepth() + " tag=" + parser.getName());
6685 } else {
6686 reportSettingsProblem(Log.WARN,
6687 "Unknown element under <preferred-activities>: "
6688 + parser.getName());
6689 XmlUtils.skipCurrentTag(parser);
6690 }
6691 }
6692
6693 if (setPos != setCount) {
6694 if (mParseError == null) {
6695 mParseError = "Not enough set tags (expected " + setCount
6696 + " but found " + setPos + ") in " + mShortActivity;
6697 }
6698 }
6699
6700 mSetPackages = myPackages;
6701 mSetClasses = myClasses;
6702 mSetComponents = myComponents;
6703 }
6704
6705 public void writeToXml(XmlSerializer serializer) throws IOException {
6706 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6707 serializer.attribute(null, "name", mShortActivity);
6708 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6709 serializer.attribute(null, "set", Integer.toString(NS));
6710 for (int s=0; s<NS; s++) {
6711 serializer.startTag(null, "set");
6712 serializer.attribute(null, "name", mSetComponents[s]);
6713 serializer.endTag(null, "set");
6714 }
6715 serializer.startTag(null, "filter");
6716 super.writeToXml(serializer);
6717 serializer.endTag(null, "filter");
6718 }
6719
6720 boolean sameSet(List<ResolveInfo> query, int priority) {
6721 if (mSetPackages == null) return false;
6722 final int NQ = query.size();
6723 final int NS = mSetPackages.length;
6724 int numMatch = 0;
6725 for (int i=0; i<NQ; i++) {
6726 ResolveInfo ri = query.get(i);
6727 if (ri.priority != priority) continue;
6728 ActivityInfo ai = ri.activityInfo;
6729 boolean good = false;
6730 for (int j=0; j<NS; j++) {
6731 if (mSetPackages[j].equals(ai.packageName)
6732 && mSetClasses[j].equals(ai.name)) {
6733 numMatch++;
6734 good = true;
6735 break;
6736 }
6737 }
6738 if (!good) return false;
6739 }
6740 return numMatch == NS;
6741 }
6742 }
6743
6744 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006745 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 HashSet<String> grantedPermissions = new HashSet<String>();
6748 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006753 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6754 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6755 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 }
6757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 /**
6760 * Settings base class for pending and resolved classes.
6761 */
6762 static class PackageSettingBase extends GrantedPermissions {
6763 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006764 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006765 File codePath;
6766 String codePathString;
6767 File resourcePath;
6768 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 private long timeStamp;
6770 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006771 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006773 boolean uidError;
6774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 PackageSignatures signatures = new PackageSignatures();
6776
6777 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 /* Explicitly disabled components */
6780 HashSet<String> disabledComponents = new HashSet<String>(0);
6781 /* Explicitly enabled components */
6782 HashSet<String> enabledComponents = new HashSet<String>(0);
6783 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6784 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006785
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006786 PackageSettingBase origPackage;
6787
Jacek Surazski65e13172009-04-28 15:26:38 +02006788 /* package name of the app that installed this package */
6789 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006790
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006791 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006792 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 super(pkgFlags);
6794 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006795 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006796 init(codePath, resourcePath, pVersionCode);
6797 }
6798
6799 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 this.codePath = codePath;
6801 this.codePathString = codePath.toString();
6802 this.resourcePath = resourcePath;
6803 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006804 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006806
Jacek Surazski65e13172009-04-28 15:26:38 +02006807 public void setInstallerPackageName(String packageName) {
6808 installerPackageName = packageName;
6809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006810
Jacek Surazski65e13172009-04-28 15:26:38 +02006811 String getInstallerPackageName() {
6812 return installerPackageName;
6813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 public void setInstallStatus(int newStatus) {
6816 installStatus = newStatus;
6817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006819 public int getInstallStatus() {
6820 return installStatus;
6821 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 public void setTimeStamp(long newStamp) {
6824 if (newStamp != timeStamp) {
6825 timeStamp = newStamp;
6826 timeStampString = Long.toString(newStamp);
6827 }
6828 }
6829
6830 public void setTimeStamp(long newStamp, String newStampStr) {
6831 timeStamp = newStamp;
6832 timeStampString = newStampStr;
6833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 public long getTimeStamp() {
6836 return timeStamp;
6837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 public String getTimeStampStr() {
6840 return timeStampString;
6841 }
6842
6843 public void copyFrom(PackageSettingBase base) {
6844 grantedPermissions = base.grantedPermissions;
6845 gids = base.gids;
6846 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848 timeStamp = base.timeStamp;
6849 timeStampString = base.timeStampString;
6850 signatures = base.signatures;
6851 permissionsFixed = base.permissionsFixed;
6852 disabledComponents = base.disabledComponents;
6853 enabledComponents = base.enabledComponents;
6854 enabled = base.enabled;
6855 installStatus = base.installStatus;
6856 }
6857
6858 void enableComponentLP(String componentClassName) {
6859 disabledComponents.remove(componentClassName);
6860 enabledComponents.add(componentClassName);
6861 }
6862
6863 void disableComponentLP(String componentClassName) {
6864 enabledComponents.remove(componentClassName);
6865 disabledComponents.add(componentClassName);
6866 }
6867
6868 void restoreComponentLP(String componentClassName) {
6869 enabledComponents.remove(componentClassName);
6870 disabledComponents.remove(componentClassName);
6871 }
6872
6873 int currentEnabledStateLP(String componentName) {
6874 if (enabledComponents.contains(componentName)) {
6875 return COMPONENT_ENABLED_STATE_ENABLED;
6876 } else if (disabledComponents.contains(componentName)) {
6877 return COMPONENT_ENABLED_STATE_DISABLED;
6878 } else {
6879 return COMPONENT_ENABLED_STATE_DEFAULT;
6880 }
6881 }
6882 }
6883
6884 /**
6885 * Settings data for a particular package we know about.
6886 */
6887 static final class PackageSetting extends PackageSettingBase {
6888 int userId;
6889 PackageParser.Package pkg;
6890 SharedUserSetting sharedUser;
6891
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006892 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006893 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006894 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 @Override
6898 public String toString() {
6899 return "PackageSetting{"
6900 + Integer.toHexString(System.identityHashCode(this))
6901 + " " + name + "/" + userId + "}";
6902 }
6903 }
6904
6905 /**
6906 * Settings data for a particular shared user ID we know about.
6907 */
6908 static final class SharedUserSetting extends GrantedPermissions {
6909 final String name;
6910 int userId;
6911 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6912 final PackageSignatures signatures = new PackageSignatures();
6913
6914 SharedUserSetting(String _name, int _pkgFlags) {
6915 super(_pkgFlags);
6916 name = _name;
6917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 @Override
6920 public String toString() {
6921 return "SharedUserSetting{"
6922 + Integer.toHexString(System.identityHashCode(this))
6923 + " " + name + "/" + userId + "}";
6924 }
6925 }
6926
6927 /**
6928 * Holds information about dynamic settings.
6929 */
6930 private static final class Settings {
6931 private final File mSettingsFilename;
6932 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08006933 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006934 private final HashMap<String, PackageSetting> mPackages =
6935 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 // List of replaced system applications
6937 final HashMap<String, PackageSetting> mDisabledSysPackages =
6938 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006940 // The user's preferred activities associated with particular intent
6941 // filters.
6942 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6943 new IntentResolver<PreferredActivity, PreferredActivity>() {
6944 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006945 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006947 out.print(prefix); out.print(
6948 Integer.toHexString(System.identityHashCode(filter)));
6949 out.print(' ');
6950 out.print(filter.mActivity.flattenToShortString());
6951 out.print(" match=0x");
6952 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006953 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006954 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006955 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006956 out.print(prefix); out.print(" ");
6957 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 }
6959 }
6960 }
6961 };
6962 private final HashMap<String, SharedUserSetting> mSharedUsers =
6963 new HashMap<String, SharedUserSetting>();
6964 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6965 private final SparseArray<Object> mOtherUserIds =
6966 new SparseArray<Object>();
6967
6968 // For reading/writing settings file.
6969 private final ArrayList<Signature> mPastSignatures =
6970 new ArrayList<Signature>();
6971
6972 // Mapping from permission names to info about them.
6973 final HashMap<String, BasePermission> mPermissions =
6974 new HashMap<String, BasePermission>();
6975
6976 // Mapping from permission tree names to info about them.
6977 final HashMap<String, BasePermission> mPermissionTrees =
6978 new HashMap<String, BasePermission>();
6979
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006980 // Packages that have been uninstalled and still need their external
6981 // storage data deleted.
6982 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
6983
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006984 // Packages that have been renamed since they were first installed.
6985 // Keys are the new names of the packages, values are the original
6986 // names. The packages appear everwhere else under their original
6987 // names.
6988 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
6989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 private final StringBuilder mReadMessages = new StringBuilder();
6991
6992 private static final class PendingPackage extends PackageSettingBase {
6993 final int sharedId;
6994
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006995 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006996 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006997 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 this.sharedId = sharedId;
6999 }
7000 }
7001 private final ArrayList<PendingPackage> mPendingPackages
7002 = new ArrayList<PendingPackage>();
7003
7004 Settings() {
7005 File dataDir = Environment.getDataDirectory();
7006 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007007 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7008 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007010 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 FileUtils.setPermissions(systemDir.toString(),
7012 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7013 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7014 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007015 FileUtils.setPermissions(systemSecureDir.toString(),
7016 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7017 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7018 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 mSettingsFilename = new File(systemDir, "packages.xml");
7020 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007021 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 }
7023
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007024 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007025 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 int pkgFlags, boolean create, boolean add) {
7027 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007028 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007029 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 return p;
7031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007032
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007033 PackageSetting peekPackageLP(String name) {
7034 return mPackages.get(name);
7035 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 PackageSetting p = mPackages.get(name);
7037 if (p != null && p.codePath.getPath().equals(codePath)) {
7038 return p;
7039 }
7040 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007041 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 void setInstallStatus(String pkgName, int status) {
7045 PackageSetting p = mPackages.get(pkgName);
7046 if(p != null) {
7047 if(p.getInstallStatus() != status) {
7048 p.setInstallStatus(status);
7049 }
7050 }
7051 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007052
Jacek Surazski65e13172009-04-28 15:26:38 +02007053 void setInstallerPackageName(String pkgName,
7054 String installerPkgName) {
7055 PackageSetting p = mPackages.get(pkgName);
7056 if(p != null) {
7057 p.setInstallerPackageName(installerPkgName);
7058 }
7059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007060
Jacek Surazski65e13172009-04-28 15:26:38 +02007061 String getInstallerPackageName(String pkgName) {
7062 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007063 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007064 }
7065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 int getInstallStatus(String pkgName) {
7067 PackageSetting p = mPackages.get(pkgName);
7068 if(p != null) {
7069 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007071 return -1;
7072 }
7073
7074 SharedUserSetting getSharedUserLP(String name,
7075 int pkgFlags, boolean create) {
7076 SharedUserSetting s = mSharedUsers.get(name);
7077 if (s == null) {
7078 if (!create) {
7079 return null;
7080 }
7081 s = new SharedUserSetting(name, pkgFlags);
7082 if (MULTIPLE_APPLICATION_UIDS) {
7083 s.userId = newUserIdLP(s);
7084 } else {
7085 s.userId = FIRST_APPLICATION_UID;
7086 }
7087 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7088 // < 0 means we couldn't assign a userid; fall out and return
7089 // s, which is currently null
7090 if (s.userId >= 0) {
7091 mSharedUsers.put(name, s);
7092 }
7093 }
7094
7095 return s;
7096 }
7097
7098 int disableSystemPackageLP(String name) {
7099 PackageSetting p = mPackages.get(name);
7100 if(p == null) {
7101 Log.w(TAG, "Package:"+name+" is not an installed package");
7102 return -1;
7103 }
7104 PackageSetting dp = mDisabledSysPackages.get(name);
7105 // always make sure the system package code and resource paths dont change
7106 if(dp == null) {
7107 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7108 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7109 }
7110 mDisabledSysPackages.put(name, p);
7111 }
7112 return removePackageLP(name);
7113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 PackageSetting enableSystemPackageLP(String name) {
7116 PackageSetting p = mDisabledSysPackages.get(name);
7117 if(p == null) {
7118 Log.w(TAG, "Package:"+name+" is not disabled");
7119 return null;
7120 }
7121 // Reset flag in ApplicationInfo object
7122 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7123 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7124 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007125 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007126 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 mDisabledSysPackages.remove(name);
7128 return ret;
7129 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007130
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007131 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007132 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 PackageSetting p = mPackages.get(name);
7134 if (p != null) {
7135 if (p.userId == uid) {
7136 return p;
7137 }
7138 reportSettingsProblem(Log.ERROR,
7139 "Adding duplicate package, keeping first: " + name);
7140 return null;
7141 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007142 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 p.userId = uid;
7144 if (addUserIdLP(uid, p, name)) {
7145 mPackages.put(name, p);
7146 return p;
7147 }
7148 return null;
7149 }
7150
7151 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7152 SharedUserSetting s = mSharedUsers.get(name);
7153 if (s != null) {
7154 if (s.userId == uid) {
7155 return s;
7156 }
7157 reportSettingsProblem(Log.ERROR,
7158 "Adding duplicate shared user, keeping first: " + name);
7159 return null;
7160 }
7161 s = new SharedUserSetting(name, pkgFlags);
7162 s.userId = uid;
7163 if (addUserIdLP(uid, s, name)) {
7164 mSharedUsers.put(name, s);
7165 return s;
7166 }
7167 return null;
7168 }
7169
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007170 // Transfer ownership of permissions from one package to another.
7171 private void transferPermissions(String origPkg, String newPkg) {
7172 // Transfer ownership of permissions to the new package.
7173 for (int i=0; i<2; i++) {
7174 HashMap<String, BasePermission> permissions =
7175 i == 0 ? mPermissionTrees : mPermissions;
7176 for (BasePermission bp : permissions.values()) {
7177 if (origPkg.equals(bp.sourcePackage)) {
7178 if (DEBUG_UPGRADE) Log.v(TAG,
7179 "Moving permission " + bp.name
7180 + " from pkg " + bp.sourcePackage
7181 + " to " + newPkg);
7182 bp.sourcePackage = newPkg;
7183 bp.perm = null;
7184 if (bp.pendingInfo != null) {
7185 bp.sourcePackage = newPkg;
7186 }
7187 bp.uid = 0;
7188 bp.gids = null;
7189 }
7190 }
7191 }
7192 }
7193
7194 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007195 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007196 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 PackageSetting p = mPackages.get(name);
7198 if (p != null) {
7199 if (!p.codePath.equals(codePath)) {
7200 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007201 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007202 // This is an updated system app with versions in both system
7203 // and data partition. Just let the most recent version
7204 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007205 Log.w(TAG, "Trying to update system app code path from " +
7206 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007207 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007208 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007209 reportSettingsProblem(Log.WARN,
7210 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007211 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007213 }
7214 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 reportSettingsProblem(Log.WARN,
7216 "Package " + name + " shared user changed from "
7217 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7218 + " to "
7219 + (sharedUser != null ? sharedUser.name : "<nothing>")
7220 + "; replacing with new");
7221 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007222 } else {
7223 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7224 // If what we are scanning is a system package, then
7225 // make it so, regardless of whether it was previously
7226 // installed only in the data partition.
7227 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 }
7230 }
7231 if (p == null) {
7232 // Create a new PackageSettings entry. this can end up here because
7233 // of code path mismatch or user id mismatch of an updated system partition
7234 if (!create) {
7235 return null;
7236 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007237 if (origPackage != null) {
7238 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007239 p = new PackageSetting(origPackage.name, name, codePath,
7240 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007241 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7242 + " is adopting original package " + origPackage.name);
7243 p.copyFrom(origPackage);
7244 p.sharedUser = origPackage.sharedUser;
7245 p.userId = origPackage.userId;
7246 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007247 mRenamedPackages.put(name, origPackage.name);
7248 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007249 // Update new package state.
7250 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007251 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007252 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007253 p.setTimeStamp(codePath.lastModified());
7254 p.sharedUser = sharedUser;
7255 if (sharedUser != null) {
7256 p.userId = sharedUser.userId;
7257 } else if (MULTIPLE_APPLICATION_UIDS) {
7258 // Clone the setting here for disabled system packages
7259 PackageSetting dis = mDisabledSysPackages.get(name);
7260 if (dis != null) {
7261 // For disabled packages a new setting is created
7262 // from the existing user id. This still has to be
7263 // added to list of user id's
7264 // Copy signatures from previous setting
7265 if (dis.signatures.mSignatures != null) {
7266 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7267 }
7268 p.userId = dis.userId;
7269 // Clone permissions
7270 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7271 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7272 // Clone component info
7273 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7274 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7275 // Add new setting to list of user ids
7276 addUserIdLP(p.userId, p, name);
7277 } else {
7278 // Assign new user id
7279 p.userId = newUserIdLP(p);
7280 }
7281 } else {
7282 p.userId = FIRST_APPLICATION_UID;
7283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 }
7285 if (p.userId < 0) {
7286 reportSettingsProblem(Log.WARN,
7287 "Package " + name + " could not be assigned a valid uid");
7288 return null;
7289 }
7290 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007291 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007293 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007294 }
7295 }
7296 return p;
7297 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007298
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007299 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007300 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007301 String codePath = pkg.applicationInfo.sourceDir;
7302 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007303 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007304 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007305 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007306 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007307 p.codePath = new File(codePath);
7308 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007309 }
7310 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007311 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007312 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007313 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007314 p.resourcePath = new File(resourcePath);
7315 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007316 }
7317 // Update version code if needed
7318 if (pkg.mVersionCode != p.versionCode) {
7319 p.versionCode = pkg.mVersionCode;
7320 }
7321 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7322 }
7323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 // Utility method that adds a PackageSetting to mPackages and
7325 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007326 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 SharedUserSetting sharedUser) {
7328 mPackages.put(name, p);
7329 if (sharedUser != null) {
7330 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7331 reportSettingsProblem(Log.ERROR,
7332 "Package " + p.name + " was user "
7333 + p.sharedUser + " but is now " + sharedUser
7334 + "; I am not changing its files so it will probably fail!");
7335 p.sharedUser.packages.remove(p);
7336 } else if (p.userId != sharedUser.userId) {
7337 reportSettingsProblem(Log.ERROR,
7338 "Package " + p.name + " was user id " + p.userId
7339 + " but is now user " + sharedUser
7340 + " with id " + sharedUser.userId
7341 + "; I am not changing its files so it will probably fail!");
7342 }
7343
7344 sharedUser.packages.add(p);
7345 p.sharedUser = sharedUser;
7346 p.userId = sharedUser.userId;
7347 }
7348 }
7349
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007350 /*
7351 * Update the shared user setting when a package using
7352 * specifying the shared user id is removed. The gids
7353 * associated with each permission of the deleted package
7354 * are removed from the shared user's gid list only if its
7355 * not in use by other permissions of packages in the
7356 * shared user setting.
7357 */
7358 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7360 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7361 return;
7362 }
7363 // No sharedUserId
7364 if (deletedPs.sharedUser == null) {
7365 return;
7366 }
7367 SharedUserSetting sus = deletedPs.sharedUser;
7368 // Update permissions
7369 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7370 boolean used = false;
7371 if (!sus.grantedPermissions.contains (eachPerm)) {
7372 continue;
7373 }
7374 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007375 if (pkg.pkg != null &&
7376 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7377 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378 used = true;
7379 break;
7380 }
7381 }
7382 if (!used) {
7383 // can safely delete this permission from list
7384 sus.grantedPermissions.remove(eachPerm);
7385 sus.loadedPermissions.remove(eachPerm);
7386 }
7387 }
7388 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007389 int newGids[] = globalGids;
7390 for (String eachPerm : sus.grantedPermissions) {
7391 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007392 if (bp != null) {
7393 newGids = appendInts(newGids, bp.gids);
7394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 }
7396 sus.gids = newGids;
7397 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007399 private int removePackageLP(String name) {
7400 PackageSetting p = mPackages.get(name);
7401 if (p != null) {
7402 mPackages.remove(name);
7403 if (p.sharedUser != null) {
7404 p.sharedUser.packages.remove(p);
7405 if (p.sharedUser.packages.size() == 0) {
7406 mSharedUsers.remove(p.sharedUser.name);
7407 removeUserIdLP(p.sharedUser.userId);
7408 return p.sharedUser.userId;
7409 }
7410 } else {
7411 removeUserIdLP(p.userId);
7412 return p.userId;
7413 }
7414 }
7415 return -1;
7416 }
7417
7418 private boolean addUserIdLP(int uid, Object obj, Object name) {
7419 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7420 return false;
7421 }
7422
7423 if (uid >= FIRST_APPLICATION_UID) {
7424 int N = mUserIds.size();
7425 final int index = uid - FIRST_APPLICATION_UID;
7426 while (index >= N) {
7427 mUserIds.add(null);
7428 N++;
7429 }
7430 if (mUserIds.get(index) != null) {
7431 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007432 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 + " name=" + name);
7434 return false;
7435 }
7436 mUserIds.set(index, obj);
7437 } else {
7438 if (mOtherUserIds.get(uid) != null) {
7439 reportSettingsProblem(Log.ERROR,
7440 "Adding duplicate shared id: " + uid
7441 + " name=" + name);
7442 return false;
7443 }
7444 mOtherUserIds.put(uid, obj);
7445 }
7446 return true;
7447 }
7448
7449 public Object getUserIdLP(int uid) {
7450 if (uid >= FIRST_APPLICATION_UID) {
7451 int N = mUserIds.size();
7452 final int index = uid - FIRST_APPLICATION_UID;
7453 return index < N ? mUserIds.get(index) : null;
7454 } else {
7455 return mOtherUserIds.get(uid);
7456 }
7457 }
7458
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007459 private Set<String> findPackagesWithFlag(int flag) {
7460 Set<String> ret = new HashSet<String>();
7461 for (PackageSetting ps : mPackages.values()) {
7462 // Has to match atleast all the flag bits set on flag
7463 if ((ps.pkgFlags & flag) == flag) {
7464 ret.add(ps.name);
7465 }
7466 }
7467 return ret;
7468 }
7469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007470 private void removeUserIdLP(int uid) {
7471 if (uid >= FIRST_APPLICATION_UID) {
7472 int N = mUserIds.size();
7473 final int index = uid - FIRST_APPLICATION_UID;
7474 if (index < N) mUserIds.set(index, null);
7475 } else {
7476 mOtherUserIds.remove(uid);
7477 }
7478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 void writeLP() {
7481 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7482
7483 // Keep the old settings around until we know the new ones have
7484 // been successfully written.
7485 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007486 // Presence of backup settings file indicates that we failed
7487 // to persist settings earlier. So preserve the older
7488 // backup for future reference since the current settings
7489 // might have been corrupted.
7490 if (!mBackupSettingsFilename.exists()) {
7491 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7492 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7493 return;
7494 }
7495 } else {
7496 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007498 }
7499
7500 mPastSignatures.clear();
7501
7502 try {
7503 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7504
7505 //XmlSerializer serializer = XmlUtils.serializerInstance();
7506 XmlSerializer serializer = new FastXmlSerializer();
7507 serializer.setOutput(str, "utf-8");
7508 serializer.startDocument(null, true);
7509 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7510
7511 serializer.startTag(null, "packages");
7512
7513 serializer.startTag(null, "permission-trees");
7514 for (BasePermission bp : mPermissionTrees.values()) {
7515 writePermission(serializer, bp);
7516 }
7517 serializer.endTag(null, "permission-trees");
7518
7519 serializer.startTag(null, "permissions");
7520 for (BasePermission bp : mPermissions.values()) {
7521 writePermission(serializer, bp);
7522 }
7523 serializer.endTag(null, "permissions");
7524
7525 for (PackageSetting pkg : mPackages.values()) {
7526 writePackage(serializer, pkg);
7527 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7530 writeDisabledSysPackage(serializer, pkg);
7531 }
7532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 serializer.startTag(null, "preferred-activities");
7534 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7535 serializer.startTag(null, "item");
7536 pa.writeToXml(serializer);
7537 serializer.endTag(null, "item");
7538 }
7539 serializer.endTag(null, "preferred-activities");
7540
7541 for (SharedUserSetting usr : mSharedUsers.values()) {
7542 serializer.startTag(null, "shared-user");
7543 serializer.attribute(null, "name", usr.name);
7544 serializer.attribute(null, "userId",
7545 Integer.toString(usr.userId));
7546 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7547 serializer.startTag(null, "perms");
7548 for (String name : usr.grantedPermissions) {
7549 serializer.startTag(null, "item");
7550 serializer.attribute(null, "name", name);
7551 serializer.endTag(null, "item");
7552 }
7553 serializer.endTag(null, "perms");
7554 serializer.endTag(null, "shared-user");
7555 }
7556
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007557 if (mPackagesToBeCleaned.size() > 0) {
7558 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7559 serializer.startTag(null, "cleaning-package");
7560 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7561 serializer.endTag(null, "cleaning-package");
7562 }
7563 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007564
7565 if (mRenamedPackages.size() > 0) {
7566 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7567 serializer.startTag(null, "renamed-package");
7568 serializer.attribute(null, "new", e.getKey());
7569 serializer.attribute(null, "old", e.getValue());
7570 serializer.endTag(null, "renamed-package");
7571 }
7572 }
7573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 serializer.endTag(null, "packages");
7575
7576 serializer.endDocument();
7577
7578 str.flush();
7579 str.close();
7580
7581 // New settings successfully written, old ones are no longer
7582 // needed.
7583 mBackupSettingsFilename.delete();
7584 FileUtils.setPermissions(mSettingsFilename.toString(),
7585 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7586 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7587 |FileUtils.S_IROTH,
7588 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007589
7590 // Write package list file now, use a JournaledFile.
7591 //
7592 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7593 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7594
7595 str = new FileOutputStream(journal.chooseForWrite());
7596 try {
7597 StringBuilder sb = new StringBuilder();
7598 for (PackageSetting pkg : mPackages.values()) {
7599 ApplicationInfo ai = pkg.pkg.applicationInfo;
7600 String dataPath = ai.dataDir;
7601 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7602
7603 // Avoid any application that has a space in its path
7604 // or that is handled by the system.
7605 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7606 continue;
7607
7608 // we store on each line the following information for now:
7609 //
7610 // pkgName - package name
7611 // userId - application-specific user id
7612 // debugFlag - 0 or 1 if the package is debuggable.
7613 // dataPath - path to package's data path
7614 //
7615 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7616 //
7617 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7618 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7619 // system/core/run-as/run-as.c
7620 //
7621 sb.setLength(0);
7622 sb.append(ai.packageName);
7623 sb.append(" ");
7624 sb.append((int)ai.uid);
7625 sb.append(isDebug ? " 1 " : " 0 ");
7626 sb.append(dataPath);
7627 sb.append("\n");
7628 str.write(sb.toString().getBytes());
7629 }
7630 str.flush();
7631 str.close();
7632 journal.commit();
7633 }
7634 catch (Exception e) {
7635 journal.rollback();
7636 }
7637
7638 FileUtils.setPermissions(mPackageListFilename.toString(),
7639 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7640 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7641 |FileUtils.S_IROTH,
7642 -1, -1);
7643
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007644 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645
7646 } catch(XmlPullParserException e) {
7647 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 -08007648 } catch(java.io.IOException e) {
7649 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 -08007650 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007651 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007652 if (mSettingsFilename.exists()) {
7653 if (!mSettingsFilename.delete()) {
7654 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7655 }
7656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 //Debug.stopMethodTracing();
7658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007659
7660 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007661 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 serializer.startTag(null, "updated-package");
7663 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007664 if (pkg.realName != null) {
7665 serializer.attribute(null, "realName", pkg.realName);
7666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 serializer.attribute(null, "codePath", pkg.codePathString);
7668 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007669 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7671 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7672 }
7673 if (pkg.sharedUser == null) {
7674 serializer.attribute(null, "userId",
7675 Integer.toString(pkg.userId));
7676 } else {
7677 serializer.attribute(null, "sharedUserId",
7678 Integer.toString(pkg.userId));
7679 }
7680 serializer.startTag(null, "perms");
7681 if (pkg.sharedUser == null) {
7682 // If this is a shared user, the permissions will
7683 // be written there. We still need to write an
7684 // empty permissions list so permissionsFixed will
7685 // be set.
7686 for (final String name : pkg.grantedPermissions) {
7687 BasePermission bp = mPermissions.get(name);
7688 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7689 // We only need to write signature or system permissions but this wont
7690 // match the semantics of grantedPermissions. So write all permissions.
7691 serializer.startTag(null, "item");
7692 serializer.attribute(null, "name", name);
7693 serializer.endTag(null, "item");
7694 }
7695 }
7696 }
7697 serializer.endTag(null, "perms");
7698 serializer.endTag(null, "updated-package");
7699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007700
7701 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007702 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 serializer.startTag(null, "package");
7704 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007705 if (pkg.realName != null) {
7706 serializer.attribute(null, "realName", pkg.realName);
7707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 serializer.attribute(null, "codePath", pkg.codePathString);
7709 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7710 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7711 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007712 serializer.attribute(null, "flags",
7713 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007715 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 if (pkg.sharedUser == null) {
7717 serializer.attribute(null, "userId",
7718 Integer.toString(pkg.userId));
7719 } else {
7720 serializer.attribute(null, "sharedUserId",
7721 Integer.toString(pkg.userId));
7722 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007723 if (pkg.uidError) {
7724 serializer.attribute(null, "uidError", "true");
7725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7727 serializer.attribute(null, "enabled",
7728 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7729 ? "true" : "false");
7730 }
7731 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7732 serializer.attribute(null, "installStatus", "false");
7733 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007734 if (pkg.installerPackageName != null) {
7735 serializer.attribute(null, "installer", pkg.installerPackageName);
7736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7738 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7739 serializer.startTag(null, "perms");
7740 if (pkg.sharedUser == null) {
7741 // If this is a shared user, the permissions will
7742 // be written there. We still need to write an
7743 // empty permissions list so permissionsFixed will
7744 // be set.
7745 for (final String name : pkg.grantedPermissions) {
7746 serializer.startTag(null, "item");
7747 serializer.attribute(null, "name", name);
7748 serializer.endTag(null, "item");
7749 }
7750 }
7751 serializer.endTag(null, "perms");
7752 }
7753 if (pkg.disabledComponents.size() > 0) {
7754 serializer.startTag(null, "disabled-components");
7755 for (final String name : pkg.disabledComponents) {
7756 serializer.startTag(null, "item");
7757 serializer.attribute(null, "name", name);
7758 serializer.endTag(null, "item");
7759 }
7760 serializer.endTag(null, "disabled-components");
7761 }
7762 if (pkg.enabledComponents.size() > 0) {
7763 serializer.startTag(null, "enabled-components");
7764 for (final String name : pkg.enabledComponents) {
7765 serializer.startTag(null, "item");
7766 serializer.attribute(null, "name", name);
7767 serializer.endTag(null, "item");
7768 }
7769 serializer.endTag(null, "enabled-components");
7770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 serializer.endTag(null, "package");
7773 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 void writePermission(XmlSerializer serializer, BasePermission bp)
7776 throws XmlPullParserException, java.io.IOException {
7777 if (bp.type != BasePermission.TYPE_BUILTIN
7778 && bp.sourcePackage != null) {
7779 serializer.startTag(null, "item");
7780 serializer.attribute(null, "name", bp.name);
7781 serializer.attribute(null, "package", bp.sourcePackage);
7782 if (DEBUG_SETTINGS) Log.v(TAG,
7783 "Writing perm: name=" + bp.name + " type=" + bp.type);
7784 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7785 PermissionInfo pi = bp.perm != null ? bp.perm.info
7786 : bp.pendingInfo;
7787 if (pi != null) {
7788 serializer.attribute(null, "type", "dynamic");
7789 if (pi.icon != 0) {
7790 serializer.attribute(null, "icon",
7791 Integer.toString(pi.icon));
7792 }
7793 if (pi.nonLocalizedLabel != null) {
7794 serializer.attribute(null, "label",
7795 pi.nonLocalizedLabel.toString());
7796 }
7797 if (pi.protectionLevel !=
7798 PermissionInfo.PROTECTION_NORMAL) {
7799 serializer.attribute(null, "protection",
7800 Integer.toString(pi.protectionLevel));
7801 }
7802 }
7803 }
7804 serializer.endTag(null, "item");
7805 }
7806 }
7807
7808 String getReadMessagesLP() {
7809 return mReadMessages.toString();
7810 }
7811
Oscar Montemayora8529f62009-11-18 10:14:20 -08007812 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7814 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007815 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 while(its.hasNext()) {
7817 String key = its.next();
7818 PackageSetting ps = mPackages.get(key);
7819 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007820 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 }
7822 }
7823 return ret;
7824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 boolean readLP() {
7827 FileInputStream str = null;
7828 if (mBackupSettingsFilename.exists()) {
7829 try {
7830 str = new FileInputStream(mBackupSettingsFilename);
7831 mReadMessages.append("Reading from backup settings file\n");
7832 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007833 if (mSettingsFilename.exists()) {
7834 // If both the backup and settings file exist, we
7835 // ignore the settings since it might have been
7836 // corrupted.
7837 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7838 mSettingsFilename.delete();
7839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 } catch (java.io.IOException e) {
7841 // We'll try for the normal settings file.
7842 }
7843 }
7844
7845 mPastSignatures.clear();
7846
7847 try {
7848 if (str == null) {
7849 if (!mSettingsFilename.exists()) {
7850 mReadMessages.append("No settings file found\n");
7851 Log.i(TAG, "No current settings file!");
7852 return false;
7853 }
7854 str = new FileInputStream(mSettingsFilename);
7855 }
7856 XmlPullParser parser = Xml.newPullParser();
7857 parser.setInput(str, null);
7858
7859 int type;
7860 while ((type=parser.next()) != XmlPullParser.START_TAG
7861 && type != XmlPullParser.END_DOCUMENT) {
7862 ;
7863 }
7864
7865 if (type != XmlPullParser.START_TAG) {
7866 mReadMessages.append("No start tag found in settings file\n");
7867 Log.e(TAG, "No start tag found in package manager settings");
7868 return false;
7869 }
7870
7871 int outerDepth = parser.getDepth();
7872 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7873 && (type != XmlPullParser.END_TAG
7874 || parser.getDepth() > outerDepth)) {
7875 if (type == XmlPullParser.END_TAG
7876 || type == XmlPullParser.TEXT) {
7877 continue;
7878 }
7879
7880 String tagName = parser.getName();
7881 if (tagName.equals("package")) {
7882 readPackageLP(parser);
7883 } else if (tagName.equals("permissions")) {
7884 readPermissionsLP(mPermissions, parser);
7885 } else if (tagName.equals("permission-trees")) {
7886 readPermissionsLP(mPermissionTrees, parser);
7887 } else if (tagName.equals("shared-user")) {
7888 readSharedUserLP(parser);
7889 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007890 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 } else if (tagName.equals("preferred-activities")) {
7892 readPreferredActivitiesLP(parser);
7893 } else if(tagName.equals("updated-package")) {
7894 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007895 } else if (tagName.equals("cleaning-package")) {
7896 String name = parser.getAttributeValue(null, "name");
7897 if (name != null) {
7898 mPackagesToBeCleaned.add(name);
7899 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007900 } else if (tagName.equals("renamed-package")) {
7901 String nname = parser.getAttributeValue(null, "new");
7902 String oname = parser.getAttributeValue(null, "old");
7903 if (nname != null && oname != null) {
7904 mRenamedPackages.put(nname, oname);
7905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 } else {
7907 Log.w(TAG, "Unknown element under <packages>: "
7908 + parser.getName());
7909 XmlUtils.skipCurrentTag(parser);
7910 }
7911 }
7912
7913 str.close();
7914
7915 } catch(XmlPullParserException e) {
7916 mReadMessages.append("Error reading: " + e.toString());
7917 Log.e(TAG, "Error reading package manager settings", e);
7918
7919 } catch(java.io.IOException e) {
7920 mReadMessages.append("Error reading: " + e.toString());
7921 Log.e(TAG, "Error reading package manager settings", e);
7922
7923 }
7924
7925 int N = mPendingPackages.size();
7926 for (int i=0; i<N; i++) {
7927 final PendingPackage pp = mPendingPackages.get(i);
7928 Object idObj = getUserIdLP(pp.sharedId);
7929 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007930 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007932 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 if (p == null) {
7934 Log.w(TAG, "Unable to create application package for "
7935 + pp.name);
7936 continue;
7937 }
7938 p.copyFrom(pp);
7939 } else if (idObj != null) {
7940 String msg = "Bad package setting: package " + pp.name
7941 + " has shared uid " + pp.sharedId
7942 + " that is not a shared uid\n";
7943 mReadMessages.append(msg);
7944 Log.e(TAG, msg);
7945 } else {
7946 String msg = "Bad package setting: package " + pp.name
7947 + " has shared uid " + pp.sharedId
7948 + " that is not defined\n";
7949 mReadMessages.append(msg);
7950 Log.e(TAG, msg);
7951 }
7952 }
7953 mPendingPackages.clear();
7954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 mReadMessages.append("Read completed successfully: "
7956 + mPackages.size() + " packages, "
7957 + mSharedUsers.size() + " shared uids\n");
7958
7959 return true;
7960 }
7961
7962 private int readInt(XmlPullParser parser, String ns, String name,
7963 int defValue) {
7964 String v = parser.getAttributeValue(ns, name);
7965 try {
7966 if (v == null) {
7967 return defValue;
7968 }
7969 return Integer.parseInt(v);
7970 } catch (NumberFormatException e) {
7971 reportSettingsProblem(Log.WARN,
7972 "Error in package manager settings: attribute " +
7973 name + " has bad integer value " + v + " at "
7974 + parser.getPositionDescription());
7975 }
7976 return defValue;
7977 }
7978
7979 private void readPermissionsLP(HashMap<String, BasePermission> out,
7980 XmlPullParser parser)
7981 throws IOException, XmlPullParserException {
7982 int outerDepth = parser.getDepth();
7983 int type;
7984 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7985 && (type != XmlPullParser.END_TAG
7986 || parser.getDepth() > outerDepth)) {
7987 if (type == XmlPullParser.END_TAG
7988 || type == XmlPullParser.TEXT) {
7989 continue;
7990 }
7991
7992 String tagName = parser.getName();
7993 if (tagName.equals("item")) {
7994 String name = parser.getAttributeValue(null, "name");
7995 String sourcePackage = parser.getAttributeValue(null, "package");
7996 String ptype = parser.getAttributeValue(null, "type");
7997 if (name != null && sourcePackage != null) {
7998 boolean dynamic = "dynamic".equals(ptype);
7999 BasePermission bp = new BasePermission(name, sourcePackage,
8000 dynamic
8001 ? BasePermission.TYPE_DYNAMIC
8002 : BasePermission.TYPE_NORMAL);
8003 if (dynamic) {
8004 PermissionInfo pi = new PermissionInfo();
8005 pi.packageName = sourcePackage.intern();
8006 pi.name = name.intern();
8007 pi.icon = readInt(parser, null, "icon", 0);
8008 pi.nonLocalizedLabel = parser.getAttributeValue(
8009 null, "label");
8010 pi.protectionLevel = readInt(parser, null, "protection",
8011 PermissionInfo.PROTECTION_NORMAL);
8012 bp.pendingInfo = pi;
8013 }
8014 out.put(bp.name, bp);
8015 } else {
8016 reportSettingsProblem(Log.WARN,
8017 "Error in package manager settings: permissions has"
8018 + " no name at " + parser.getPositionDescription());
8019 }
8020 } else {
8021 reportSettingsProblem(Log.WARN,
8022 "Unknown element reading permissions: "
8023 + parser.getName() + " at "
8024 + parser.getPositionDescription());
8025 }
8026 XmlUtils.skipCurrentTag(parser);
8027 }
8028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008031 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008033 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 String codePathStr = parser.getAttributeValue(null, "codePath");
8035 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008036 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 resourcePathStr = codePathStr;
8038 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008039 String version = parser.getAttributeValue(null, "version");
8040 int versionCode = 0;
8041 if (version != null) {
8042 try {
8043 versionCode = Integer.parseInt(version);
8044 } catch (NumberFormatException e) {
8045 }
8046 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008048 int pkgFlags = 0;
8049 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008050 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008051 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008052 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 String timeStampStr = parser.getAttributeValue(null, "ts");
8054 if (timeStampStr != null) {
8055 try {
8056 long timeStamp = Long.parseLong(timeStampStr);
8057 ps.setTimeStamp(timeStamp, timeStampStr);
8058 } catch (NumberFormatException e) {
8059 }
8060 }
8061 String idStr = parser.getAttributeValue(null, "userId");
8062 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8063 if(ps.userId <= 0) {
8064 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8065 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8066 }
8067 int outerDepth = parser.getDepth();
8068 int type;
8069 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8070 && (type != XmlPullParser.END_TAG
8071 || parser.getDepth() > outerDepth)) {
8072 if (type == XmlPullParser.END_TAG
8073 || type == XmlPullParser.TEXT) {
8074 continue;
8075 }
8076
8077 String tagName = parser.getName();
8078 if (tagName.equals("perms")) {
8079 readGrantedPermissionsLP(parser,
8080 ps.grantedPermissions);
8081 } else {
8082 reportSettingsProblem(Log.WARN,
8083 "Unknown element under <updated-package>: "
8084 + parser.getName());
8085 XmlUtils.skipCurrentTag(parser);
8086 }
8087 }
8088 mDisabledSysPackages.put(name, ps);
8089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 private void readPackageLP(XmlPullParser parser)
8092 throws XmlPullParserException, IOException {
8093 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008094 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 String idStr = null;
8096 String sharedIdStr = null;
8097 String codePathStr = null;
8098 String resourcePathStr = null;
8099 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008100 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008101 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 int pkgFlags = 0;
8103 String timeStampStr;
8104 long timeStamp = 0;
8105 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008106 String version = null;
8107 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 try {
8109 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008110 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008111 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008112 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8114 codePathStr = parser.getAttributeValue(null, "codePath");
8115 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008116 version = parser.getAttributeValue(null, "version");
8117 if (version != null) {
8118 try {
8119 versionCode = Integer.parseInt(version);
8120 } catch (NumberFormatException e) {
8121 }
8122 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008123 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008124
8125 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008127 try {
8128 pkgFlags = Integer.parseInt(systemStr);
8129 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 }
8131 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008132 // For backward compatibility
8133 systemStr = parser.getAttributeValue(null, "system");
8134 if (systemStr != null) {
8135 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8136 } else {
8137 // Old settings that don't specify system... just treat
8138 // them as system, good enough.
8139 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142 timeStampStr = parser.getAttributeValue(null, "ts");
8143 if (timeStampStr != null) {
8144 try {
8145 timeStamp = Long.parseLong(timeStampStr);
8146 } catch (NumberFormatException e) {
8147 }
8148 }
8149 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8150 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8151 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8152 if (resourcePathStr == null) {
8153 resourcePathStr = codePathStr;
8154 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008155 if (realName != null) {
8156 realName = realName.intern();
8157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 if (name == null) {
8159 reportSettingsProblem(Log.WARN,
8160 "Error in package manager settings: <package> has no name at "
8161 + parser.getPositionDescription());
8162 } else if (codePathStr == null) {
8163 reportSettingsProblem(Log.WARN,
8164 "Error in package manager settings: <package> has no codePath at "
8165 + parser.getPositionDescription());
8166 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008167 packageSetting = addPackageLP(name.intern(), realName,
8168 new File(codePathStr), new File(resourcePathStr),
8169 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8171 + ": userId=" + userId + " pkg=" + packageSetting);
8172 if (packageSetting == null) {
8173 reportSettingsProblem(Log.ERROR,
8174 "Failure adding uid " + userId
8175 + " while parsing settings at "
8176 + parser.getPositionDescription());
8177 } else {
8178 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8179 }
8180 } else if (sharedIdStr != null) {
8181 userId = sharedIdStr != null
8182 ? Integer.parseInt(sharedIdStr) : 0;
8183 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008184 packageSetting = new PendingPackage(name.intern(), realName,
8185 new File(codePathStr), new File(resourcePathStr),
8186 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8188 mPendingPackages.add((PendingPackage) packageSetting);
8189 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8190 + ": sharedUserId=" + userId + " pkg="
8191 + packageSetting);
8192 } else {
8193 reportSettingsProblem(Log.WARN,
8194 "Error in package manager settings: package "
8195 + name + " has bad sharedId " + sharedIdStr
8196 + " at " + parser.getPositionDescription());
8197 }
8198 } else {
8199 reportSettingsProblem(Log.WARN,
8200 "Error in package manager settings: package "
8201 + name + " has bad userId " + idStr + " at "
8202 + parser.getPositionDescription());
8203 }
8204 } catch (NumberFormatException e) {
8205 reportSettingsProblem(Log.WARN,
8206 "Error in package manager settings: package "
8207 + name + " has bad userId " + idStr + " at "
8208 + parser.getPositionDescription());
8209 }
8210 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008211 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008212 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 final String enabledStr = parser.getAttributeValue(null, "enabled");
8214 if (enabledStr != null) {
8215 if (enabledStr.equalsIgnoreCase("true")) {
8216 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8217 } else if (enabledStr.equalsIgnoreCase("false")) {
8218 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8219 } else if (enabledStr.equalsIgnoreCase("default")) {
8220 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8221 } else {
8222 reportSettingsProblem(Log.WARN,
8223 "Error in package manager settings: package "
8224 + name + " has bad enabled value: " + idStr
8225 + " at " + parser.getPositionDescription());
8226 }
8227 } else {
8228 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8229 }
8230 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8231 if (installStatusStr != null) {
8232 if (installStatusStr.equalsIgnoreCase("false")) {
8233 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8234 } else {
8235 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8236 }
8237 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008239 int outerDepth = parser.getDepth();
8240 int type;
8241 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8242 && (type != XmlPullParser.END_TAG
8243 || parser.getDepth() > outerDepth)) {
8244 if (type == XmlPullParser.END_TAG
8245 || type == XmlPullParser.TEXT) {
8246 continue;
8247 }
8248
8249 String tagName = parser.getName();
8250 if (tagName.equals("disabled-components")) {
8251 readDisabledComponentsLP(packageSetting, parser);
8252 } else if (tagName.equals("enabled-components")) {
8253 readEnabledComponentsLP(packageSetting, parser);
8254 } else if (tagName.equals("sigs")) {
8255 packageSetting.signatures.readXml(parser, mPastSignatures);
8256 } else if (tagName.equals("perms")) {
8257 readGrantedPermissionsLP(parser,
8258 packageSetting.loadedPermissions);
8259 packageSetting.permissionsFixed = true;
8260 } else {
8261 reportSettingsProblem(Log.WARN,
8262 "Unknown element under <package>: "
8263 + parser.getName());
8264 XmlUtils.skipCurrentTag(parser);
8265 }
8266 }
8267 } else {
8268 XmlUtils.skipCurrentTag(parser);
8269 }
8270 }
8271
8272 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8273 XmlPullParser parser)
8274 throws IOException, XmlPullParserException {
8275 int outerDepth = parser.getDepth();
8276 int type;
8277 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8278 && (type != XmlPullParser.END_TAG
8279 || parser.getDepth() > outerDepth)) {
8280 if (type == XmlPullParser.END_TAG
8281 || type == XmlPullParser.TEXT) {
8282 continue;
8283 }
8284
8285 String tagName = parser.getName();
8286 if (tagName.equals("item")) {
8287 String name = parser.getAttributeValue(null, "name");
8288 if (name != null) {
8289 packageSetting.disabledComponents.add(name.intern());
8290 } else {
8291 reportSettingsProblem(Log.WARN,
8292 "Error in package manager settings: <disabled-components> has"
8293 + " no name at " + parser.getPositionDescription());
8294 }
8295 } else {
8296 reportSettingsProblem(Log.WARN,
8297 "Unknown element under <disabled-components>: "
8298 + parser.getName());
8299 }
8300 XmlUtils.skipCurrentTag(parser);
8301 }
8302 }
8303
8304 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8305 XmlPullParser parser)
8306 throws IOException, XmlPullParserException {
8307 int outerDepth = parser.getDepth();
8308 int type;
8309 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8310 && (type != XmlPullParser.END_TAG
8311 || parser.getDepth() > outerDepth)) {
8312 if (type == XmlPullParser.END_TAG
8313 || type == XmlPullParser.TEXT) {
8314 continue;
8315 }
8316
8317 String tagName = parser.getName();
8318 if (tagName.equals("item")) {
8319 String name = parser.getAttributeValue(null, "name");
8320 if (name != null) {
8321 packageSetting.enabledComponents.add(name.intern());
8322 } else {
8323 reportSettingsProblem(Log.WARN,
8324 "Error in package manager settings: <enabled-components> has"
8325 + " no name at " + parser.getPositionDescription());
8326 }
8327 } else {
8328 reportSettingsProblem(Log.WARN,
8329 "Unknown element under <enabled-components>: "
8330 + parser.getName());
8331 }
8332 XmlUtils.skipCurrentTag(parser);
8333 }
8334 }
8335
8336 private void readSharedUserLP(XmlPullParser parser)
8337 throws XmlPullParserException, IOException {
8338 String name = null;
8339 String idStr = null;
8340 int pkgFlags = 0;
8341 SharedUserSetting su = null;
8342 try {
8343 name = parser.getAttributeValue(null, "name");
8344 idStr = parser.getAttributeValue(null, "userId");
8345 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8346 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8347 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8348 }
8349 if (name == null) {
8350 reportSettingsProblem(Log.WARN,
8351 "Error in package manager settings: <shared-user> has no name at "
8352 + parser.getPositionDescription());
8353 } else if (userId == 0) {
8354 reportSettingsProblem(Log.WARN,
8355 "Error in package manager settings: shared-user "
8356 + name + " has bad userId " + idStr + " at "
8357 + parser.getPositionDescription());
8358 } else {
8359 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8360 reportSettingsProblem(Log.ERROR,
8361 "Occurred while parsing settings at "
8362 + parser.getPositionDescription());
8363 }
8364 }
8365 } catch (NumberFormatException e) {
8366 reportSettingsProblem(Log.WARN,
8367 "Error in package manager settings: package "
8368 + name + " has bad userId " + idStr + " at "
8369 + parser.getPositionDescription());
8370 };
8371
8372 if (su != null) {
8373 int outerDepth = parser.getDepth();
8374 int type;
8375 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8376 && (type != XmlPullParser.END_TAG
8377 || parser.getDepth() > outerDepth)) {
8378 if (type == XmlPullParser.END_TAG
8379 || type == XmlPullParser.TEXT) {
8380 continue;
8381 }
8382
8383 String tagName = parser.getName();
8384 if (tagName.equals("sigs")) {
8385 su.signatures.readXml(parser, mPastSignatures);
8386 } else if (tagName.equals("perms")) {
8387 readGrantedPermissionsLP(parser, su.loadedPermissions);
8388 } else {
8389 reportSettingsProblem(Log.WARN,
8390 "Unknown element under <shared-user>: "
8391 + parser.getName());
8392 XmlUtils.skipCurrentTag(parser);
8393 }
8394 }
8395
8396 } else {
8397 XmlUtils.skipCurrentTag(parser);
8398 }
8399 }
8400
8401 private void readGrantedPermissionsLP(XmlPullParser parser,
8402 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8403 int outerDepth = parser.getDepth();
8404 int type;
8405 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8406 && (type != XmlPullParser.END_TAG
8407 || parser.getDepth() > outerDepth)) {
8408 if (type == XmlPullParser.END_TAG
8409 || type == XmlPullParser.TEXT) {
8410 continue;
8411 }
8412
8413 String tagName = parser.getName();
8414 if (tagName.equals("item")) {
8415 String name = parser.getAttributeValue(null, "name");
8416 if (name != null) {
8417 outPerms.add(name.intern());
8418 } else {
8419 reportSettingsProblem(Log.WARN,
8420 "Error in package manager settings: <perms> has"
8421 + " no name at " + parser.getPositionDescription());
8422 }
8423 } else {
8424 reportSettingsProblem(Log.WARN,
8425 "Unknown element under <perms>: "
8426 + parser.getName());
8427 }
8428 XmlUtils.skipCurrentTag(parser);
8429 }
8430 }
8431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 private void readPreferredActivitiesLP(XmlPullParser parser)
8433 throws XmlPullParserException, IOException {
8434 int outerDepth = parser.getDepth();
8435 int type;
8436 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8437 && (type != XmlPullParser.END_TAG
8438 || parser.getDepth() > outerDepth)) {
8439 if (type == XmlPullParser.END_TAG
8440 || type == XmlPullParser.TEXT) {
8441 continue;
8442 }
8443
8444 String tagName = parser.getName();
8445 if (tagName.equals("item")) {
8446 PreferredActivity pa = new PreferredActivity(parser);
8447 if (pa.mParseError == null) {
8448 mPreferredActivities.addFilter(pa);
8449 } else {
8450 reportSettingsProblem(Log.WARN,
8451 "Error in package manager settings: <preferred-activity> "
8452 + pa.mParseError + " at "
8453 + parser.getPositionDescription());
8454 }
8455 } else {
8456 reportSettingsProblem(Log.WARN,
8457 "Unknown element under <preferred-activities>: "
8458 + parser.getName());
8459 XmlUtils.skipCurrentTag(parser);
8460 }
8461 }
8462 }
8463
8464 // Returns -1 if we could not find an available UserId to assign
8465 private int newUserIdLP(Object obj) {
8466 // Let's be stupidly inefficient for now...
8467 final int N = mUserIds.size();
8468 for (int i=0; i<N; i++) {
8469 if (mUserIds.get(i) == null) {
8470 mUserIds.set(i, obj);
8471 return FIRST_APPLICATION_UID + i;
8472 }
8473 }
8474
8475 // None left?
8476 if (N >= MAX_APPLICATION_UIDS) {
8477 return -1;
8478 }
8479
8480 mUserIds.add(obj);
8481 return FIRST_APPLICATION_UID + N;
8482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 public PackageSetting getDisabledSystemPkg(String name) {
8485 synchronized(mPackages) {
8486 PackageSetting ps = mDisabledSysPackages.get(name);
8487 return ps;
8488 }
8489 }
8490
8491 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8492 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8493 if (Config.LOGV) {
8494 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8495 + " componentName = " + componentInfo.name);
8496 Log.v(TAG, "enabledComponents: "
8497 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8498 Log.v(TAG, "disabledComponents: "
8499 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8500 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008501 if (packageSettings == null) {
8502 if (false) {
8503 Log.w(TAG, "WAITING FOR DEBUGGER");
8504 Debug.waitForDebugger();
8505 Log.i(TAG, "We will crash!");
8506 }
8507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8509 || ((componentInfo.enabled
8510 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8511 || (componentInfo.applicationInfo.enabled
8512 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8513 && !packageSettings.disabledComponents.contains(componentInfo.name))
8514 || packageSettings.enabledComponents.contains(componentInfo.name));
8515 }
8516 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008517
8518 // ------- apps on sdcard specific code -------
8519 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008520 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008521 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008522 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008523 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008524
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008525
8526 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008527 return (MountService) ServiceManager.getService("mount");
8528 }
8529
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008530 private String getEncryptKey() {
8531 try {
8532 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8533 if (sdEncKey == null) {
8534 sdEncKey = SystemKeyStore.getInstance().
8535 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8536 if (sdEncKey == null) {
8537 Log.e(TAG, "Failed to create encryption keys");
8538 return null;
8539 }
8540 }
8541 return sdEncKey;
8542 } catch (NoSuchAlgorithmException nsae) {
8543 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8544 return null;
8545 }
8546 }
8547
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008548 private String createSdDir(File tmpPackageFile, String pkgName) {
8549 // Create mount point via MountService
8550 MountService mountService = getMountService();
8551 long len = tmpPackageFile.length();
8552 int mbLen = (int) (len/(1024*1024));
8553 if ((len - (mbLen * 1024 * 1024)) > 0) {
8554 mbLen++;
8555 }
8556 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
8557 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008558 String sdEncKey;
8559 try {
8560 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8561 if (sdEncKey == null) {
8562 sdEncKey = SystemKeyStore.getInstance().
8563 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8564 if (sdEncKey == null) {
8565 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
8566 return null;
8567 }
8568 }
8569 } catch (NoSuchAlgorithmException nsae) {
8570 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8571 return null;
8572 }
San Mehatbe16cb12010-01-29 05:35:35 -08008573
8574 int rc = mountService.createSecureContainer(
8575 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008576 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008577 Log.e(TAG, String.format("Failed to create container (%d)", rc));
8578
8579 rc = mountService.destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008580 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008581 Log.e(TAG, String.format("Failed to cleanup container (%d)", rc));
8582 return null;
8583 }
8584 rc = mountService.createSecureContainer(
8585 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008586 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008587 Log.e(TAG, String.format("Failed to create container (2nd try) (%d)", rc));
8588 return null;
8589 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008590 }
San Mehatbe16cb12010-01-29 05:35:35 -08008591
8592 cachePath = mountService.getSecureContainerPath(pkgName);
8593 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008594 return cachePath;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008595 }
8596
8597 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08008598 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8599 if (sdEncKey == null) {
8600 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
8601 return null;
8602 }
San Mehatbe16cb12010-01-29 05:35:35 -08008603
8604 int rc = getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
8605
San Mehatb1043402010-02-05 08:26:50 -08008606 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008607 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " rc : " + rc);
8608 return null;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008609 }
San Mehatbe16cb12010-01-29 05:35:35 -08008610
8611 return getMountService().getSecureContainerPath(pkgName);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008612 }
8613
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008614 private boolean unMountSdDir(String pkgName) {
8615 // STOPSHIP unmount directory
San Mehatbe16cb12010-01-29 05:35:35 -08008616 int rc = getMountService().unmountSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008617 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008618 Log.e(TAG, "Failed to unmount : " + pkgName + " with rc " + rc);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008619 return false;
8620 }
San Mehatbe16cb12010-01-29 05:35:35 -08008621 return true;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008622 }
8623
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008624 private boolean renameSdDir(String oldId, String newId) {
8625 try {
8626 getMountService().renameSecureContainer(oldId, newId);
8627 return true;
8628 } catch (IllegalStateException e) {
8629 Log.i(TAG, "Failed ot rename " + oldId + " to " + newId +
8630 " with exception : " + e);
8631 }
8632 return false;
8633 }
8634
8635 private String getSdDir(String pkgName) {
8636 return getMountService().getSecureContainerPath(pkgName);
8637 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008638
San Mehatbe16cb12010-01-29 05:35:35 -08008639 private boolean finalizeSdDir(String pkgName) {
8640 int rc = getMountService().finalizeSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008641 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008642 Log.i(TAG, "Failed to finalize container for pkg : " + pkgName);
8643 return false;
8644 }
8645 return true;
8646 }
8647
8648 private boolean destroySdDir(String pkgName) {
8649 int rc = getMountService().destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008650 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008651 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8652 return false;
8653 }
8654 return true;
8655 }
8656
8657 static String[] getSecureContainerList() {
8658 String[] list = getMountService().getSecureContainerList();
8659 return list.length == 0 ? null : list;
8660 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008661
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008662 static boolean isContainerMounted(String cid) {
8663 // STOPSHIP
8664 // New api from MountService
8665 try {
8666 return (getMountService().getSecureContainerPath(cid) != null);
8667 } catch (IllegalStateException e) {
8668 }
8669 return false;
8670 }
8671
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008672 static String getTempContainerId() {
8673 String prefix = "smdl1tmp";
8674 int tmpIdx = 1;
8675 String list[] = getSecureContainerList();
8676 if (list != null) {
8677 int idx = 0;
8678 int idList[] = new int[MAX_CONTAINERS];
8679 boolean neverFound = true;
8680 for (String name : list) {
8681 // Ignore null entries
8682 if (name == null) {
8683 continue;
8684 }
8685 int sidx = name.indexOf(prefix);
8686 if (sidx == -1) {
8687 // Not a temp file. just ignore
8688 continue;
8689 }
8690 String subStr = name.substring(sidx + prefix.length());
8691 idList[idx] = -1;
8692 if (subStr != null) {
8693 try {
8694 int cid = Integer.parseInt(subStr);
8695 idList[idx++] = cid;
8696 neverFound = false;
8697 } catch (NumberFormatException e) {
8698 }
8699 }
8700 }
8701 if (!neverFound) {
8702 // Sort idList
8703 Arrays.sort(idList);
8704 for (int j = 1; j <= idList.length; j++) {
8705 if (idList[j-1] != j) {
8706 tmpIdx = j;
8707 break;
8708 }
8709 }
8710 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008711 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008712 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008713 }
8714
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008715 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008716 synchronized (mPackages) {
8717 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8718 mediaStatus+", mMediaMounted=" + mMediaMounted);
8719 if (mediaStatus == mMediaMounted) {
8720 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008721 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008722 mMediaMounted = mediaStatus;
8723 // Queue up an async operation since the package installation may take a little while.
8724 mHandler.post(new Runnable() {
8725 public void run() {
8726 mHandler.removeCallbacks(this);
8727 updateExternalMediaStatusInner(mediaStatus);
8728 }
8729 });
8730 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008731 }
8732
8733 void updateExternalMediaStatusInner(boolean mediaStatus) {
8734 final String list[] = getSecureContainerList();
8735 if (list == null || list.length == 0) {
8736 return;
8737 }
8738 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8739 int uidList[] = new int[list.length];
8740 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008741 synchronized (mPackages) {
8742 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8743 for (String cid : list) {
8744 SdInstallArgs args = new SdInstallArgs(cid);
8745 String removeEntry = null;
8746 for (String app : appList) {
8747 if (args.matchContainer(app)) {
8748 removeEntry = app;
8749 break;
8750 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008751 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008752 if (removeEntry == null) {
8753 // No matching app on device. Skip entry or may be cleanup?
8754 // Ignore default package
8755 continue;
8756 }
8757 appList.remove(removeEntry);
8758 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8759 processCids.put(args, ps.codePathString);
8760 int uid = ps.userId;
8761 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008762 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008763 }
8764 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008765 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008766 int uidArr[] = null;
8767 if (num > 0) {
8768 // Sort uid list
8769 Arrays.sort(uidList, 0, num);
8770 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008771 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008772 uidArr[0] = uidList[0];
8773 int di = 0;
8774 for (int i = 1; i < num; i++) {
8775 if (uidList[i-1] != uidList[i]) {
8776 uidArr[di++] = uidList[i];
8777 }
8778 }
8779 if (true) {
8780 for (int j = 0; j < num; j++) {
8781 Log.i(TAG, "uidArr[" + j + "]=" + uidArr[j]);
8782 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008783 }
8784 }
8785 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008786 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008787 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008788 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008789 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008790 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008791 unloadMediaPackages(processCids, uidArr);
8792 }
8793 }
8794
8795 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8796 ArrayList<String> pkgList, int uidArr[]) {
8797 int size = pkgList.size();
8798 if (size > 0) {
8799 // Send broadcasts here
8800 Bundle extras = new Bundle();
8801 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8802 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008803 if (uidArr != null) {
8804 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8805 }
8806 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8807 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008808 sendPackageBroadcast(action, null, extras);
8809 }
8810 }
8811
8812 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8813 ArrayList<String> pkgList = new ArrayList<String>();
8814 Set<SdInstallArgs> keys = processCids.keySet();
8815 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008816 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008817 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8818 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008819 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008820 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008821 continue;
8822 }
8823 // Parse package
8824 int parseFlags = PackageParser.PARSE_CHATTY |
8825 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8826 PackageParser pp = new PackageParser(codePath);
8827 pp.setSeparateProcesses(mSeparateProcesses);
8828 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8829 codePath, mMetrics, parseFlags);
8830 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008831 Log.e(TAG, "Trying to install pkg : "
8832 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008833 continue;
8834 }
8835 setApplicationInfoPaths(pkg, codePath, codePath);
8836 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8837 synchronized (mInstallLock) {
8838 // Scan the package
8839 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8840 synchronized (mPackages) {
8841 // Grant permissions
8842 grantPermissionsLP(pkg, false);
8843 // Persist settings
8844 mSettings.writeLP();
8845 retCode = PackageManager.INSTALL_SUCCEEDED;
8846 pkgList.add(pkg.packageName);
8847 }
8848 } else {
8849 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8850 }
8851 }
8852 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008853 }
8854 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008855 if (pkgList.size() > 0) {
8856 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8857 Runtime.getRuntime().gc();
8858 // If something failed do we clean up here or next install?
8859 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008860 }
8861
8862 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008863 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008864 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008865 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008866 Set<SdInstallArgs> keys = processCids.keySet();
8867 for (SdInstallArgs args : keys) {
8868 String cid = args.cid;
8869 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008870 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008871 // Delete package internally
8872 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8873 synchronized (mInstallLock) {
8874 boolean res = deletePackageLI(pkgName, false,
8875 PackageManager.DONT_DELETE_DATA, outInfo);
8876 if (res) {
8877 pkgList.add(pkgName);
8878 } else {
8879 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008880 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008881 }
8882 }
8883 }
8884 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008885 if (pkgList.size() > 0) {
8886 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8887 Runtime.getRuntime().gc();
8888 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008889 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008890 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008891 synchronized (mInstallLock) {
8892 args.doPostDeleteLI(false);
8893 }
8894 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896}