blob: cd4ae4ccd0b053334254f7080c93f0ebfc513fbf [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023
24import org.xmlpull.v1.XmlPullParser;
25import org.xmlpull.v1.XmlPullParserException;
26import org.xmlpull.v1.XmlSerializer;
27
28import android.app.ActivityManagerNative;
29import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070034import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080035import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070036import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.pm.ActivityInfo;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070040import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.IPackageDataObserver;
42import android.content.pm.IPackageDeleteObserver;
43import android.content.pm.IPackageInstallObserver;
44import android.content.pm.IPackageManager;
45import android.content.pm.IPackageStatsObserver;
46import android.content.pm.InstrumentationInfo;
47import android.content.pm.PackageInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.PackageStats;
50import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
51import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
52import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
53import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
54import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
55import android.content.pm.PackageParser;
56import android.content.pm.PermissionInfo;
57import android.content.pm.PermissionGroupInfo;
58import android.content.pm.ProviderInfo;
59import android.content.pm.ResolveInfo;
60import android.content.pm.ServiceInfo;
61import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.Uri;
63import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070064import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.Bundle;
66import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080067import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070068import android.os.Looper;
69import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Parcel;
71import android.os.RemoteException;
72import android.os.Environment;
73import android.os.FileObserver;
74import android.os.FileUtils;
75import android.os.Handler;
76import android.os.ParcelFileDescriptor;
77import android.os.Process;
78import android.os.ServiceManager;
79import android.os.SystemClock;
80import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080081import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.util.*;
83import android.view.Display;
84import android.view.WindowManager;
85
86import java.io.File;
87import java.io.FileDescriptor;
88import java.io.FileInputStream;
89import java.io.FileNotFoundException;
90import java.io.FileOutputStream;
91import java.io.FileReader;
92import java.io.FilenameFilter;
93import java.io.IOException;
94import java.io.InputStream;
95import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080096import java.security.NoSuchAlgorithmException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.util.ArrayList;
98import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -070099import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.Collections;
101import java.util.Comparator;
102import java.util.Enumeration;
103import java.util.HashMap;
104import java.util.HashSet;
105import java.util.Iterator;
106import java.util.List;
107import java.util.Map;
108import java.util.Set;
109import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800110import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.zip.ZipFile;
112import java.util.zip.ZipOutputStream;
113
114class PackageManagerService extends IPackageManager.Stub {
115 private static final String TAG = "PackageManager";
116 private static final boolean DEBUG_SETTINGS = false;
117 private static final boolean DEBUG_PREFERRED = false;
118
119 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
120 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400121 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final int FIRST_APPLICATION_UID =
123 Process.FIRST_APPLICATION_UID;
124 private static final int MAX_APPLICATION_UIDS = 1000;
125
126 private static final boolean SHOW_INFO = false;
127
128 private static final boolean GET_CERTIFICATES = true;
129
Oscar Montemayora8529f62009-11-18 10:14:20 -0800130 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final int REMOVE_EVENTS =
133 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
134 private static final int ADD_EVENTS =
135 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
136
137 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
138
139 static final int SCAN_MONITOR = 1<<0;
140 static final int SCAN_NO_DEX = 1<<1;
141 static final int SCAN_FORCE_DEX = 1<<2;
142 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800143 static final int SCAN_NEW_INSTALL = 1<<4;
144 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
147 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700148 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Dianne Hackborn851a5412009-05-08 12:06:44 -0700150 final int mSdkVersion = Build.VERSION.SDK_INT;
151 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
152 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 final Context mContext;
155 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700156 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 final DisplayMetrics mMetrics;
158 final int mDefParseFlags;
159 final String[] mSeparateProcesses;
160
161 // This is where all application persistent data goes.
162 final File mAppDataDir;
163
Oscar Montemayora8529f62009-11-18 10:14:20 -0800164 // If Encrypted File System feature is enabled, all application persistent data
165 // should go here instead.
166 final File mSecureAppDataDir;
167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 // This is the object monitoring the framework dir.
169 final FileObserver mFrameworkInstallObserver;
170
171 // This is the object monitoring the system app dir.
172 final FileObserver mSystemInstallObserver;
173
174 // This is the object monitoring mAppInstallDir.
175 final FileObserver mAppInstallObserver;
176
177 // This is the object monitoring mDrmAppPrivateInstallDir.
178 final FileObserver mDrmAppInstallObserver;
179
180 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
181 // LOCK HELD. Can be called with mInstallLock held.
182 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 final File mFrameworkDir;
185 final File mSystemAppDir;
186 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700187 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
189 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
190 // apps.
191 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 // Lock for state used when installing and doing other long running
196 // operations. Methods that must be called with this lock held have
197 // the prefix "LI".
198 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 // These are the directories in the 3rd party applications installed dir
201 // that we have currently loaded packages from. Keys are the application's
202 // installed zip file (absolute codePath), and values are Package.
203 final HashMap<String, PackageParser.Package> mAppDirs =
204 new HashMap<String, PackageParser.Package>();
205
206 // Information for the parser to write more useful error messages.
207 File mScanningPath;
208 int mLastScanError;
209
210 final int[] mOutPermissions = new int[3];
211
212 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // Keys are String (package name), values are Package. This also serves
215 // as the lock for the global state. Methods that must be called with
216 // this lock held have the prefix "LP".
217 final HashMap<String, PackageParser.Package> mPackages =
218 new HashMap<String, PackageParser.Package>();
219
220 final Settings mSettings;
221 boolean mRestoredSettings;
222 boolean mReportedUidError;
223
224 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
225 int[] mGlobalGids;
226
227 // These are the built-in uid -> permission mappings that were read from the
228 // etc/permissions.xml file.
229 final SparseArray<HashSet<String>> mSystemPermissions =
230 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // These are the built-in shared libraries that were read from the
233 // etc/permissions.xml file.
234 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800235
Dianne Hackborn49237342009-08-27 20:08:01 -0700236 // Temporary for building the final shared libraries for an .apk.
237 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800238
Dianne Hackborn49237342009-08-27 20:08:01 -0700239 // These are the features this devices supports that were read from the
240 // etc/permissions.xml file.
241 final HashMap<String, FeatureInfo> mAvailableFeatures =
242 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // All available activities, for your resolving pleasure.
245 final ActivityIntentResolver mActivities =
246 new ActivityIntentResolver();
247
248 // All available receivers, for your resolving pleasure.
249 final ActivityIntentResolver mReceivers =
250 new ActivityIntentResolver();
251
252 // All available services, for your resolving pleasure.
253 final ServiceIntentResolver mServices = new ServiceIntentResolver();
254
255 // Keys are String (provider class name), values are Provider.
256 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
257 new HashMap<ComponentName, PackageParser.Provider>();
258
259 // Mapping from provider base names (first directory in content URI codePath)
260 // to the provider information.
261 final HashMap<String, PackageParser.Provider> mProviders =
262 new HashMap<String, PackageParser.Provider>();
263
264 // Mapping from instrumentation class names to info about them.
265 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
266 new HashMap<ComponentName, PackageParser.Instrumentation>();
267
268 // Mapping from permission names to info about them.
269 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
270 new HashMap<String, PackageParser.PermissionGroup>();
271
Dianne Hackborn854060af2009-07-09 18:14:31 -0700272 // Broadcast actions that are only available to the system.
273 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 boolean mSystemReady;
276 boolean mSafeMode;
277 boolean mHasSystemUidErrors;
278
279 ApplicationInfo mAndroidApplication;
280 final ActivityInfo mResolveActivity = new ActivityInfo();
281 final ResolveInfo mResolveInfo = new ResolveInfo();
282 ComponentName mResolveComponentName;
283 PackageParser.Package mPlatformPackage;
284
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700285 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800286 final HashMap<String, ArrayList<String>> mPendingBroadcasts
287 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700288 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800289 static final int MCS_BOUND = 3;
290 static final int END_COPY = 4;
291 static final int INIT_COPY = 5;
292 static final int MCS_UNBIND = 6;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700293 // Delay time in millisecs
294 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800295 private ServiceConnection mDefContainerConn = new ServiceConnection() {
296 public void onServiceConnected(ComponentName name, IBinder service) {
297 IMediaContainerService imcs =
298 IMediaContainerService.Stub.asInterface(service);
299 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
300 mHandler.sendMessage(msg);
301 }
302
303 public void onServiceDisconnected(ComponentName name) {
304 }
305 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700306
307 class PackageHandler extends Handler {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800308 final ArrayList<InstallArgs> mPendingInstalls =
309 new ArrayList<InstallArgs>();
310 // Service Connection to remote media container service to copy
311 // package uri's from external media onto secure containers
312 // or internal storage.
313 private IMediaContainerService mContainerService = null;
314
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700315 PackageHandler(Looper looper) {
316 super(looper);
317 }
318 public void handleMessage(Message msg) {
319 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800320 case INIT_COPY: {
321 InstallArgs args = (InstallArgs) msg.obj;
322 args.createCopyFile();
323 Intent service = new Intent().setComponent(new ComponentName(
324 "com.android.defcontainer",
325 "com.android.defcontainer.DefaultContainerService"));
326 if (mContainerService != null) {
327 // No need to add to pending list. Use remote stub directly
328 handleStartCopy(args);
329 } else {
330 if (mContext.bindService(service, mDefContainerConn,
331 Context.BIND_AUTO_CREATE)) {
332 mPendingInstalls.add(args);
333 } else {
334 Log.e(TAG, "Failed to bind to media container service");
335 // Indicate install failure TODO add new error code
336 processPendingInstall(args,
337 PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800338 }
339 }
340 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800341 }
342 case MCS_BOUND: {
343 // Initialize mContainerService if needed.
344 if (msg.obj != null) {
345 mContainerService = (IMediaContainerService) msg.obj;
346 }
347 if (mPendingInstalls.size() > 0) {
348 InstallArgs args = mPendingInstalls.remove(0);
349 if (args != null) {
350 handleStartCopy(args);
351 }
352 }
353 break;
354 }
355 case MCS_UNBIND : {
356 if (mPendingInstalls.size() == 0) {
357 mContext.unbindService(mDefContainerConn);
358 mContainerService = null;
359 }
360 break;
361 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700362 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800363 String packages[];
364 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700365 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700366 int uids[];
367 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800368 if (mPendingBroadcasts == null) {
369 return;
370 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700371 size = mPendingBroadcasts.size();
372 if (size <= 0) {
373 // Nothing to be done. Just return
374 return;
375 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800376 packages = new String[size];
377 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800379 Iterator<HashMap.Entry<String, ArrayList<String>>>
380 it = mPendingBroadcasts.entrySet().iterator();
381 int i = 0;
382 while (it.hasNext() && i < size) {
383 HashMap.Entry<String, ArrayList<String>> ent = it.next();
384 packages[i] = ent.getKey();
385 components[i] = ent.getValue();
386 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700387 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800388 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700389 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800390 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700391 mPendingBroadcasts.clear();
392 }
393 // Send broadcasts
394 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800395 sendPackageChangedBroadcast(packages[i], true,
396 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 }
398 break;
399 }
400 }
401 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800402
403 // Utility method to initiate copying apk via media
404 // container service.
405 private void handleStartCopy(InstallArgs args) {
406 int ret = PackageManager.INSTALL_SUCCEEDED;
407 if (mContainerService == null) {
408 // Install error
409 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
410 } else {
411 ret = args.copyApk(mContainerService);
412 }
413 mHandler.sendEmptyMessage(MCS_UNBIND);
414 processPendingInstall(args, ret);
415 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700416 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800417
418 static boolean installOnSd(int flags) {
419 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
420 ((flags & PackageManager.INSTALL_ON_SDCARD) == 0)) {
421 return false;
422 }
423 return true;
424 }
425
426 static boolean isFwdLocked(int flags) {
427 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
428 return true;
429 }
430 return false;
431 }
432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 public static final IPackageManager main(Context context, boolean factoryTest) {
434 PackageManagerService m = new PackageManagerService(context, factoryTest);
435 ServiceManager.addService("package", m);
436 return m;
437 }
438
439 static String[] splitString(String str, char sep) {
440 int count = 1;
441 int i = 0;
442 while ((i=str.indexOf(sep, i)) >= 0) {
443 count++;
444 i++;
445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 String[] res = new String[count];
448 i=0;
449 count = 0;
450 int lastI=0;
451 while ((i=str.indexOf(sep, i)) >= 0) {
452 res[count] = str.substring(lastI, i);
453 count++;
454 i++;
455 lastI = i;
456 }
457 res[count] = str.substring(lastI, str.length());
458 return res;
459 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800462 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 if (mSdkVersion <= 0) {
466 Log.w(TAG, "**** ro.build.version.sdk not set!");
467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 mContext = context;
470 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700471 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 mMetrics = new DisplayMetrics();
473 mSettings = new Settings();
474 mSettings.addSharedUserLP("android.uid.system",
475 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
476 mSettings.addSharedUserLP("android.uid.phone",
477 MULTIPLE_APPLICATION_UIDS
478 ? RADIO_UID : FIRST_APPLICATION_UID,
479 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400480 mSettings.addSharedUserLP("android.uid.log",
481 MULTIPLE_APPLICATION_UIDS
482 ? LOG_UID : FIRST_APPLICATION_UID,
483 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484
485 String separateProcesses = SystemProperties.get("debug.separate_processes");
486 if (separateProcesses != null && separateProcesses.length() > 0) {
487 if ("*".equals(separateProcesses)) {
488 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
489 mSeparateProcesses = null;
490 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
491 } else {
492 mDefParseFlags = 0;
493 mSeparateProcesses = separateProcesses.split(",");
494 Log.w(TAG, "Running with debug.separate_processes: "
495 + separateProcesses);
496 }
497 } else {
498 mDefParseFlags = 0;
499 mSeparateProcesses = null;
500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 Installer installer = new Installer();
503 // Little hacky thing to check if installd is here, to determine
504 // whether we are running on the simulator and thus need to take
505 // care of building the /data file structure ourself.
506 // (apparently the sim now has a working installer)
507 if (installer.ping() && Process.supportsProcesses()) {
508 mInstaller = installer;
509 } else {
510 mInstaller = null;
511 }
512
513 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
514 Display d = wm.getDefaultDisplay();
515 d.getMetrics(mMetrics);
516
517 synchronized (mInstallLock) {
518 synchronized (mPackages) {
519 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 File dataDir = Environment.getDataDirectory();
523 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800524 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
526
527 if (mInstaller == null) {
528 // Make sure these dirs exist, when we are running in
529 // the simulator.
530 // Make a wide-open directory for random misc stuff.
531 File miscDir = new File(dataDir, "misc");
532 miscDir.mkdirs();
533 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800534 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 mDrmAppPrivateInstallDir.mkdirs();
536 }
537
538 readPermissions();
539
540 mRestoredSettings = mSettings.readLP();
541 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800542
543 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800545
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800546 // Set flag to monitor and not change apk file paths when
547 // scanning install directories.
548 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700549 if (mNoDexOpt) {
550 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800551 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700557 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700560 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 /**
563 * Out of paranoia, ensure that everything in the boot class
564 * path has been dexed.
565 */
566 String bootClassPath = System.getProperty("java.boot.class.path");
567 if (bootClassPath != null) {
568 String[] paths = splitString(bootClassPath, ':');
569 for (int i=0; i<paths.length; i++) {
570 try {
571 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
572 libFiles.add(paths[i]);
573 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700574 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
576 } catch (FileNotFoundException e) {
577 Log.w(TAG, "Boot class path not found: " + paths[i]);
578 } catch (IOException e) {
579 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
580 }
581 }
582 } else {
583 Log.w(TAG, "No BOOTCLASSPATH found!");
584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 /**
587 * Also ensure all external libraries have had dexopt run on them.
588 */
589 if (mSharedLibraries.size() > 0) {
590 Iterator<String> libs = mSharedLibraries.values().iterator();
591 while (libs.hasNext()) {
592 String lib = libs.next();
593 try {
594 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
595 libFiles.add(lib);
596 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700597 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
599 } catch (FileNotFoundException e) {
600 Log.w(TAG, "Library not found: " + lib);
601 } catch (IOException e) {
602 Log.w(TAG, "Exception reading library: " + lib, e);
603 }
604 }
605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 // Gross hack for now: we know this file doesn't contain any
608 // code, so don't dexopt it to avoid the resulting log spew.
609 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 /**
612 * And there are a number of commands implemented in Java, which
613 * we currently need to do the dexopt on so that they can be
614 * run from a non-root shell.
615 */
616 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700617 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 for (int i=0; i<frameworkFiles.length; i++) {
619 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
620 String path = libPath.getPath();
621 // Skip the file if we alrady did it.
622 if (libFiles.contains(path)) {
623 continue;
624 }
625 // Skip the file if it is not a type we want to dexopt.
626 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
627 continue;
628 }
629 try {
630 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
631 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700632 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 }
634 } catch (FileNotFoundException e) {
635 Log.w(TAG, "Jar not found: " + path);
636 } catch (IOException e) {
637 Log.w(TAG, "Exception reading jar: " + path, e);
638 }
639 }
640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800641
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700642 if (didDexOpt) {
643 // If we had to do a dexopt of one of the previous
644 // things, then something on the system has changed.
645 // Consider this significant, and wipe away all other
646 // existing dexopt files to ensure we don't leave any
647 // dangling around.
648 String[] files = mDalvikCacheDir.list();
649 if (files != null) {
650 for (int i=0; i<files.length; i++) {
651 String fn = files[i];
652 if (fn.startsWith("data@app@")
653 || fn.startsWith("data@app-private@")) {
654 Log.i(TAG, "Pruning dalvik file: " + fn);
655 (new File(mDalvikCacheDir, fn)).delete();
656 }
657 }
658 }
659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 mFrameworkInstallObserver = new AppDirObserver(
663 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
664 mFrameworkInstallObserver.startWatching();
665 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800666 scanMode | SCAN_NO_DEX);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
668 mSystemInstallObserver = new AppDirObserver(
669 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
670 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800671 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 mAppInstallDir = new File(dataDir, "app");
673 if (mInstaller == null) {
674 // Make sure these dirs exist, when we are running in
675 // the simulator.
676 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
677 }
678 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800679 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 //clean up list
681 for(int i = 0; i < deletePkgsList.size(); i++) {
682 //clean up here
683 cleanupInstallFailedPackage(deletePkgsList.get(i));
684 }
685 //delete tmp files
686 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800687
688 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 SystemClock.uptimeMillis());
690 mAppInstallObserver = new AppDirObserver(
691 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
692 mAppInstallObserver.startWatching();
693 scanDirLI(mAppInstallDir, 0, scanMode);
694
695 mDrmAppInstallObserver = new AppDirObserver(
696 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
697 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800698 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800700 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 SystemClock.uptimeMillis());
702 Log.i(TAG, "Time to scan packages: "
703 + ((SystemClock.uptimeMillis()-startTime)/1000f)
704 + " seconds");
705
706 updatePermissionsLP();
707
708 mSettings.writeLP();
709
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800710 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 // Now after opening every single application zip, make sure they
714 // are all flushed. Not really needed, but keeps things nice and
715 // tidy.
716 Runtime.getRuntime().gc();
717 } // synchronized (mPackages)
718 } // synchronized (mInstallLock)
719 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 @Override
722 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
723 throws RemoteException {
724 try {
725 return super.onTransact(code, data, reply, flags);
726 } catch (RuntimeException e) {
727 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
728 Log.e(TAG, "Package Manager Crash", e);
729 }
730 throw e;
731 }
732 }
733
Dianne Hackborne6620b22010-01-22 14:46:21 -0800734 void cleanupInstallFailedPackage(PackageSetting ps) {
735 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800737 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
738 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 if (retCode < 0) {
740 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800741 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 }
743 } else {
744 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800745 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 File dataDir = new File(pkg.applicationInfo.dataDir);
747 dataDir.delete();
748 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800749 if (ps.codePath != null) {
750 if (!ps.codePath.delete()) {
751 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
752 }
753 }
754 if (ps.resourcePath != null) {
755 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
756 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
757 }
758 }
759 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 }
761
762 void readPermissions() {
763 // Read permissions from .../etc/permission directory.
764 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
765 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
766 Log.w(TAG, "No directory " + libraryDir + ", skipping");
767 return;
768 }
769 if (!libraryDir.canRead()) {
770 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
771 return;
772 }
773
774 // Iterate over the files in the directory and scan .xml files
775 for (File f : libraryDir.listFiles()) {
776 // We'll read platform.xml last
777 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
778 continue;
779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 if (!f.getPath().endsWith(".xml")) {
782 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
783 continue;
784 }
785 if (!f.canRead()) {
786 Log.w(TAG, "Permissions library file " + f + " cannot be read");
787 continue;
788 }
789
790 readPermissionsFromXml(f);
791 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
794 final File permFile = new File(Environment.getRootDirectory(),
795 "etc/permissions/platform.xml");
796 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700798 StringBuilder sb = new StringBuilder(128);
799 sb.append("Libs:");
800 Iterator<String> it = mSharedLibraries.keySet().iterator();
801 while (it.hasNext()) {
802 sb.append(' ');
803 String name = it.next();
804 sb.append(name);
805 sb.append(':');
806 sb.append(mSharedLibraries.get(name));
807 }
808 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700810 sb.setLength(0);
811 sb.append("Features:");
812 it = mAvailableFeatures.keySet().iterator();
813 while (it.hasNext()) {
814 sb.append(' ');
815 sb.append(it.next());
816 }
817 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
820 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 FileReader permReader = null;
822 try {
823 permReader = new FileReader(permFile);
824 } catch (FileNotFoundException e) {
825 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
826 return;
827 }
828
829 try {
830 XmlPullParser parser = Xml.newPullParser();
831 parser.setInput(permReader);
832
833 XmlUtils.beginDocument(parser, "permissions");
834
835 while (true) {
836 XmlUtils.nextElement(parser);
837 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
838 break;
839 }
840
841 String name = parser.getName();
842 if ("group".equals(name)) {
843 String gidStr = parser.getAttributeValue(null, "gid");
844 if (gidStr != null) {
845 int gid = Integer.parseInt(gidStr);
846 mGlobalGids = appendInt(mGlobalGids, gid);
847 } else {
848 Log.w(TAG, "<group> without gid at "
849 + parser.getPositionDescription());
850 }
851
852 XmlUtils.skipCurrentTag(parser);
853 continue;
854 } else if ("permission".equals(name)) {
855 String perm = parser.getAttributeValue(null, "name");
856 if (perm == null) {
857 Log.w(TAG, "<permission> without name at "
858 + parser.getPositionDescription());
859 XmlUtils.skipCurrentTag(parser);
860 continue;
861 }
862 perm = perm.intern();
863 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } else if ("assign-permission".equals(name)) {
866 String perm = parser.getAttributeValue(null, "name");
867 if (perm == null) {
868 Log.w(TAG, "<assign-permission> without name at "
869 + parser.getPositionDescription());
870 XmlUtils.skipCurrentTag(parser);
871 continue;
872 }
873 String uidStr = parser.getAttributeValue(null, "uid");
874 if (uidStr == null) {
875 Log.w(TAG, "<assign-permission> without uid at "
876 + parser.getPositionDescription());
877 XmlUtils.skipCurrentTag(parser);
878 continue;
879 }
880 int uid = Process.getUidForName(uidStr);
881 if (uid < 0) {
882 Log.w(TAG, "<assign-permission> with unknown uid \""
883 + uidStr + "\" at "
884 + parser.getPositionDescription());
885 XmlUtils.skipCurrentTag(parser);
886 continue;
887 }
888 perm = perm.intern();
889 HashSet<String> perms = mSystemPermissions.get(uid);
890 if (perms == null) {
891 perms = new HashSet<String>();
892 mSystemPermissions.put(uid, perms);
893 }
894 perms.add(perm);
895 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } else if ("library".equals(name)) {
898 String lname = parser.getAttributeValue(null, "name");
899 String lfile = parser.getAttributeValue(null, "file");
900 if (lname == null) {
901 Log.w(TAG, "<library> without name at "
902 + parser.getPositionDescription());
903 } else if (lfile == null) {
904 Log.w(TAG, "<library> without file at "
905 + parser.getPositionDescription());
906 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700908 mSharedLibraries.put(lname, lfile);
909 }
910 XmlUtils.skipCurrentTag(parser);
911 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800912
Dianne Hackborn49237342009-08-27 20:08:01 -0700913 } else if ("feature".equals(name)) {
914 String fname = parser.getAttributeValue(null, "name");
915 if (fname == null) {
916 Log.w(TAG, "<feature> without name at "
917 + parser.getPositionDescription());
918 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700919 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700920 FeatureInfo fi = new FeatureInfo();
921 fi.name = fname;
922 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 }
924 XmlUtils.skipCurrentTag(parser);
925 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 } else {
928 XmlUtils.skipCurrentTag(parser);
929 continue;
930 }
931
932 }
933 } catch (XmlPullParserException e) {
934 Log.w(TAG, "Got execption parsing permissions.", e);
935 } catch (IOException e) {
936 Log.w(TAG, "Got execption parsing permissions.", e);
937 }
938 }
939
940 void readPermission(XmlPullParser parser, String name)
941 throws IOException, XmlPullParserException {
942
943 name = name.intern();
944
945 BasePermission bp = mSettings.mPermissions.get(name);
946 if (bp == null) {
947 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
948 mSettings.mPermissions.put(name, bp);
949 }
950 int outerDepth = parser.getDepth();
951 int type;
952 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
953 && (type != XmlPullParser.END_TAG
954 || parser.getDepth() > outerDepth)) {
955 if (type == XmlPullParser.END_TAG
956 || type == XmlPullParser.TEXT) {
957 continue;
958 }
959
960 String tagName = parser.getName();
961 if ("group".equals(tagName)) {
962 String gidStr = parser.getAttributeValue(null, "gid");
963 if (gidStr != null) {
964 int gid = Process.getGidForName(gidStr);
965 bp.gids = appendInt(bp.gids, gid);
966 } else {
967 Log.w(TAG, "<group> without gid at "
968 + parser.getPositionDescription());
969 }
970 }
971 XmlUtils.skipCurrentTag(parser);
972 }
973 }
974
975 static int[] appendInt(int[] cur, int val) {
976 if (cur == null) {
977 return new int[] { val };
978 }
979 final int N = cur.length;
980 for (int i=0; i<N; i++) {
981 if (cur[i] == val) {
982 return cur;
983 }
984 }
985 int[] ret = new int[N+1];
986 System.arraycopy(cur, 0, ret, 0, N);
987 ret[N] = val;
988 return ret;
989 }
990
991 static int[] appendInts(int[] cur, int[] add) {
992 if (add == null) return cur;
993 if (cur == null) return add;
994 final int N = add.length;
995 for (int i=0; i<N; i++) {
996 cur = appendInt(cur, add[i]);
997 }
998 return cur;
999 }
1000
1001 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001002 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1003 // The package has been uninstalled but has retained data and resources.
1004 return PackageParser.generatePackageInfo(p, null, flags);
1005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 final PackageSetting ps = (PackageSetting)p.mExtras;
1007 if (ps == null) {
1008 return null;
1009 }
1010 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1011 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1012 }
1013
1014 public PackageInfo getPackageInfo(String packageName, int flags) {
1015 synchronized (mPackages) {
1016 PackageParser.Package p = mPackages.get(packageName);
1017 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001018 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 + ": " + p);
1020 if (p != null) {
1021 return generatePackageInfo(p, flags);
1022 }
1023 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1024 return generatePackageInfoFromSettingsLP(packageName, flags);
1025 }
1026 }
1027 return null;
1028 }
1029
1030 public int getPackageUid(String packageName) {
1031 synchronized (mPackages) {
1032 PackageParser.Package p = mPackages.get(packageName);
1033 if(p != null) {
1034 return p.applicationInfo.uid;
1035 }
1036 PackageSetting ps = mSettings.mPackages.get(packageName);
1037 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1038 return -1;
1039 }
1040 p = ps.pkg;
1041 return p != null ? p.applicationInfo.uid : -1;
1042 }
1043 }
1044
1045 public int[] getPackageGids(String packageName) {
1046 synchronized (mPackages) {
1047 PackageParser.Package p = mPackages.get(packageName);
1048 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001049 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 + ": " + p);
1051 if (p != null) {
1052 final PackageSetting ps = (PackageSetting)p.mExtras;
1053 final SharedUserSetting suid = ps.sharedUser;
1054 return suid != null ? suid.gids : ps.gids;
1055 }
1056 }
1057 // stupid thing to indicate an error.
1058 return new int[0];
1059 }
1060
1061 public PermissionInfo getPermissionInfo(String name, int flags) {
1062 synchronized (mPackages) {
1063 final BasePermission p = mSettings.mPermissions.get(name);
1064 if (p != null && p.perm != null) {
1065 return PackageParser.generatePermissionInfo(p.perm, flags);
1066 }
1067 return null;
1068 }
1069 }
1070
1071 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1072 synchronized (mPackages) {
1073 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1074 for (BasePermission p : mSettings.mPermissions.values()) {
1075 if (group == null) {
1076 if (p.perm.info.group == null) {
1077 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1078 }
1079 } else {
1080 if (group.equals(p.perm.info.group)) {
1081 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1082 }
1083 }
1084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 if (out.size() > 0) {
1087 return out;
1088 }
1089 return mPermissionGroups.containsKey(group) ? out : null;
1090 }
1091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1094 synchronized (mPackages) {
1095 return PackageParser.generatePermissionGroupInfo(
1096 mPermissionGroups.get(name), flags);
1097 }
1098 }
1099
1100 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1101 synchronized (mPackages) {
1102 final int N = mPermissionGroups.size();
1103 ArrayList<PermissionGroupInfo> out
1104 = new ArrayList<PermissionGroupInfo>(N);
1105 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1106 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1107 }
1108 return out;
1109 }
1110 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1113 PackageSetting ps = mSettings.mPackages.get(packageName);
1114 if(ps != null) {
1115 if(ps.pkg == null) {
1116 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1117 if(pInfo != null) {
1118 return pInfo.applicationInfo;
1119 }
1120 return null;
1121 }
1122 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1123 }
1124 return null;
1125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1128 PackageSetting ps = mSettings.mPackages.get(packageName);
1129 if(ps != null) {
1130 if(ps.pkg == null) {
1131 ps.pkg = new PackageParser.Package(packageName);
1132 ps.pkg.applicationInfo.packageName = packageName;
1133 }
1134 return generatePackageInfo(ps.pkg, flags);
1135 }
1136 return null;
1137 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1140 synchronized (mPackages) {
1141 PackageParser.Package p = mPackages.get(packageName);
1142 if (Config.LOGV) Log.v(
1143 TAG, "getApplicationInfo " + packageName
1144 + ": " + p);
1145 if (p != null) {
1146 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001147 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 }
1149 if ("android".equals(packageName)||"system".equals(packageName)) {
1150 return mAndroidApplication;
1151 }
1152 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1153 return generateApplicationInfoFromSettingsLP(packageName, flags);
1154 }
1155 }
1156 return null;
1157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001158
1159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1161 mContext.enforceCallingOrSelfPermission(
1162 android.Manifest.permission.CLEAR_APP_CACHE, null);
1163 // Queue up an async operation since clearing cache may take a little while.
1164 mHandler.post(new Runnable() {
1165 public void run() {
1166 mHandler.removeCallbacks(this);
1167 int retCode = -1;
1168 if (mInstaller != null) {
1169 retCode = mInstaller.freeCache(freeStorageSize);
1170 if (retCode < 0) {
1171 Log.w(TAG, "Couldn't clear application caches");
1172 }
1173 } //end if mInstaller
1174 if (observer != null) {
1175 try {
1176 observer.onRemoveCompleted(null, (retCode >= 0));
1177 } catch (RemoteException e) {
1178 Log.w(TAG, "RemoveException when invoking call back");
1179 }
1180 }
1181 }
1182 });
1183 }
1184
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001185 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001186 mContext.enforceCallingOrSelfPermission(
1187 android.Manifest.permission.CLEAR_APP_CACHE, null);
1188 // Queue up an async operation since clearing cache may take a little while.
1189 mHandler.post(new Runnable() {
1190 public void run() {
1191 mHandler.removeCallbacks(this);
1192 int retCode = -1;
1193 if (mInstaller != null) {
1194 retCode = mInstaller.freeCache(freeStorageSize);
1195 if (retCode < 0) {
1196 Log.w(TAG, "Couldn't clear application caches");
1197 }
1198 }
1199 if(pi != null) {
1200 try {
1201 // Callback via pending intent
1202 int code = (retCode >= 0) ? 1 : 0;
1203 pi.sendIntent(null, code, null,
1204 null, null);
1205 } catch (SendIntentException e1) {
1206 Log.i(TAG, "Failed to send pending intent");
1207 }
1208 }
1209 }
1210 });
1211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1214 synchronized (mPackages) {
1215 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001216
1217 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001219 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
1221 if (mResolveComponentName.equals(component)) {
1222 return mResolveActivity;
1223 }
1224 }
1225 return null;
1226 }
1227
1228 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1229 synchronized (mPackages) {
1230 PackageParser.Activity a = mReceivers.mActivities.get(component);
1231 if (Config.LOGV) Log.v(
1232 TAG, "getReceiverInfo " + component + ": " + a);
1233 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1234 return PackageParser.generateActivityInfo(a, flags);
1235 }
1236 }
1237 return null;
1238 }
1239
1240 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1241 synchronized (mPackages) {
1242 PackageParser.Service s = mServices.mServices.get(component);
1243 if (Config.LOGV) Log.v(
1244 TAG, "getServiceInfo " + component + ": " + s);
1245 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1246 return PackageParser.generateServiceInfo(s, flags);
1247 }
1248 }
1249 return null;
1250 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 public String[] getSystemSharedLibraryNames() {
1253 Set<String> libSet;
1254 synchronized (mPackages) {
1255 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001256 int size = libSet.size();
1257 if (size > 0) {
1258 String[] libs = new String[size];
1259 libSet.toArray(libs);
1260 return libs;
1261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001263 return null;
1264 }
1265
1266 public FeatureInfo[] getSystemAvailableFeatures() {
1267 Collection<FeatureInfo> featSet;
1268 synchronized (mPackages) {
1269 featSet = mAvailableFeatures.values();
1270 int size = featSet.size();
1271 if (size > 0) {
1272 FeatureInfo[] features = new FeatureInfo[size+1];
1273 featSet.toArray(features);
1274 FeatureInfo fi = new FeatureInfo();
1275 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1276 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1277 features[size] = fi;
1278 return features;
1279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281 return null;
1282 }
1283
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001284 public boolean hasSystemFeature(String name) {
1285 synchronized (mPackages) {
1286 return mAvailableFeatures.containsKey(name);
1287 }
1288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 public int checkPermission(String permName, String pkgName) {
1291 synchronized (mPackages) {
1292 PackageParser.Package p = mPackages.get(pkgName);
1293 if (p != null && p.mExtras != null) {
1294 PackageSetting ps = (PackageSetting)p.mExtras;
1295 if (ps.sharedUser != null) {
1296 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1297 return PackageManager.PERMISSION_GRANTED;
1298 }
1299 } else if (ps.grantedPermissions.contains(permName)) {
1300 return PackageManager.PERMISSION_GRANTED;
1301 }
1302 }
1303 }
1304 return PackageManager.PERMISSION_DENIED;
1305 }
1306
1307 public int checkUidPermission(String permName, int uid) {
1308 synchronized (mPackages) {
1309 Object obj = mSettings.getUserIdLP(uid);
1310 if (obj != null) {
1311 if (obj instanceof SharedUserSetting) {
1312 SharedUserSetting sus = (SharedUserSetting)obj;
1313 if (sus.grantedPermissions.contains(permName)) {
1314 return PackageManager.PERMISSION_GRANTED;
1315 }
1316 } else if (obj instanceof PackageSetting) {
1317 PackageSetting ps = (PackageSetting)obj;
1318 if (ps.grantedPermissions.contains(permName)) {
1319 return PackageManager.PERMISSION_GRANTED;
1320 }
1321 }
1322 } else {
1323 HashSet<String> perms = mSystemPermissions.get(uid);
1324 if (perms != null && perms.contains(permName)) {
1325 return PackageManager.PERMISSION_GRANTED;
1326 }
1327 }
1328 }
1329 return PackageManager.PERMISSION_DENIED;
1330 }
1331
1332 private BasePermission findPermissionTreeLP(String permName) {
1333 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1334 if (permName.startsWith(bp.name) &&
1335 permName.length() > bp.name.length() &&
1336 permName.charAt(bp.name.length()) == '.') {
1337 return bp;
1338 }
1339 }
1340 return null;
1341 }
1342
1343 private BasePermission checkPermissionTreeLP(String permName) {
1344 if (permName != null) {
1345 BasePermission bp = findPermissionTreeLP(permName);
1346 if (bp != null) {
1347 if (bp.uid == Binder.getCallingUid()) {
1348 return bp;
1349 }
1350 throw new SecurityException("Calling uid "
1351 + Binder.getCallingUid()
1352 + " is not allowed to add to permission tree "
1353 + bp.name + " owned by uid " + bp.uid);
1354 }
1355 }
1356 throw new SecurityException("No permission tree found for " + permName);
1357 }
1358
1359 public boolean addPermission(PermissionInfo info) {
1360 synchronized (mPackages) {
1361 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1362 throw new SecurityException("Label must be specified in permission");
1363 }
1364 BasePermission tree = checkPermissionTreeLP(info.name);
1365 BasePermission bp = mSettings.mPermissions.get(info.name);
1366 boolean added = bp == null;
1367 if (added) {
1368 bp = new BasePermission(info.name, tree.sourcePackage,
1369 BasePermission.TYPE_DYNAMIC);
1370 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1371 throw new SecurityException(
1372 "Not allowed to modify non-dynamic permission "
1373 + info.name);
1374 }
1375 bp.perm = new PackageParser.Permission(tree.perm.owner,
1376 new PermissionInfo(info));
1377 bp.perm.info.packageName = tree.perm.info.packageName;
1378 bp.uid = tree.uid;
1379 if (added) {
1380 mSettings.mPermissions.put(info.name, bp);
1381 }
1382 mSettings.writeLP();
1383 return added;
1384 }
1385 }
1386
1387 public void removePermission(String name) {
1388 synchronized (mPackages) {
1389 checkPermissionTreeLP(name);
1390 BasePermission bp = mSettings.mPermissions.get(name);
1391 if (bp != null) {
1392 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1393 throw new SecurityException(
1394 "Not allowed to modify non-dynamic permission "
1395 + name);
1396 }
1397 mSettings.mPermissions.remove(name);
1398 mSettings.writeLP();
1399 }
1400 }
1401 }
1402
Dianne Hackborn854060af2009-07-09 18:14:31 -07001403 public boolean isProtectedBroadcast(String actionName) {
1404 synchronized (mPackages) {
1405 return mProtectedBroadcasts.contains(actionName);
1406 }
1407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 public int checkSignatures(String pkg1, String pkg2) {
1410 synchronized (mPackages) {
1411 PackageParser.Package p1 = mPackages.get(pkg1);
1412 PackageParser.Package p2 = mPackages.get(pkg2);
1413 if (p1 == null || p1.mExtras == null
1414 || p2 == null || p2.mExtras == null) {
1415 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1416 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001417 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 }
1420
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001421 public int checkUidSignatures(int uid1, int uid2) {
1422 synchronized (mPackages) {
1423 Signature[] s1;
1424 Signature[] s2;
1425 Object obj = mSettings.getUserIdLP(uid1);
1426 if (obj != null) {
1427 if (obj instanceof SharedUserSetting) {
1428 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1429 } else if (obj instanceof PackageSetting) {
1430 s1 = ((PackageSetting)obj).signatures.mSignatures;
1431 } else {
1432 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1433 }
1434 } else {
1435 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1436 }
1437 obj = mSettings.getUserIdLP(uid2);
1438 if (obj != null) {
1439 if (obj instanceof SharedUserSetting) {
1440 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1441 } else if (obj instanceof PackageSetting) {
1442 s2 = ((PackageSetting)obj).signatures.mSignatures;
1443 } else {
1444 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1445 }
1446 } else {
1447 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1448 }
1449 return checkSignaturesLP(s1, s2);
1450 }
1451 }
1452
1453 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1454 if (s1 == null) {
1455 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1457 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1458 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001459 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1461 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001462 final int N1 = s1.length;
1463 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 for (int i=0; i<N1; i++) {
1465 boolean match = false;
1466 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001467 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 match = true;
1469 break;
1470 }
1471 }
1472 if (!match) {
1473 return PackageManager.SIGNATURE_NO_MATCH;
1474 }
1475 }
1476 return PackageManager.SIGNATURE_MATCH;
1477 }
1478
1479 public String[] getPackagesForUid(int uid) {
1480 synchronized (mPackages) {
1481 Object obj = mSettings.getUserIdLP(uid);
1482 if (obj instanceof SharedUserSetting) {
1483 SharedUserSetting sus = (SharedUserSetting)obj;
1484 final int N = sus.packages.size();
1485 String[] res = new String[N];
1486 Iterator<PackageSetting> it = sus.packages.iterator();
1487 int i=0;
1488 while (it.hasNext()) {
1489 res[i++] = it.next().name;
1490 }
1491 return res;
1492 } else if (obj instanceof PackageSetting) {
1493 PackageSetting ps = (PackageSetting)obj;
1494 return new String[] { ps.name };
1495 }
1496 }
1497 return null;
1498 }
1499
1500 public String getNameForUid(int uid) {
1501 synchronized (mPackages) {
1502 Object obj = mSettings.getUserIdLP(uid);
1503 if (obj instanceof SharedUserSetting) {
1504 SharedUserSetting sus = (SharedUserSetting)obj;
1505 return sus.name + ":" + sus.userId;
1506 } else if (obj instanceof PackageSetting) {
1507 PackageSetting ps = (PackageSetting)obj;
1508 return ps.name;
1509 }
1510 }
1511 return null;
1512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 public int getUidForSharedUser(String sharedUserName) {
1515 if(sharedUserName == null) {
1516 return -1;
1517 }
1518 synchronized (mPackages) {
1519 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1520 if(suid == null) {
1521 return -1;
1522 }
1523 return suid.userId;
1524 }
1525 }
1526
1527 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1528 int flags) {
1529 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001530 return chooseBestActivity(intent, resolvedType, flags, query);
1531 }
1532
Mihai Predaeae850c2009-05-13 10:13:48 +02001533 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1534 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 if (query != null) {
1536 final int N = query.size();
1537 if (N == 1) {
1538 return query.get(0);
1539 } else if (N > 1) {
1540 // If there is more than one activity with the same priority,
1541 // then let the user decide between them.
1542 ResolveInfo r0 = query.get(0);
1543 ResolveInfo r1 = query.get(1);
1544 if (false) {
1545 System.out.println(r0.activityInfo.name +
1546 "=" + r0.priority + " vs " +
1547 r1.activityInfo.name +
1548 "=" + r1.priority);
1549 }
1550 // If the first activity has a higher priority, or a different
1551 // default, then it is always desireable to pick it.
1552 if (r0.priority != r1.priority
1553 || r0.preferredOrder != r1.preferredOrder
1554 || r0.isDefault != r1.isDefault) {
1555 return query.get(0);
1556 }
1557 // If we have saved a preference for a preferred activity for
1558 // this Intent, use that.
1559 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1560 flags, query, r0.priority);
1561 if (ri != null) {
1562 return ri;
1563 }
1564 return mResolveInfo;
1565 }
1566 }
1567 return null;
1568 }
1569
1570 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1571 int flags, List<ResolveInfo> query, int priority) {
1572 synchronized (mPackages) {
1573 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1574 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001575 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1577 if (prefs != null && prefs.size() > 0) {
1578 // First figure out how good the original match set is.
1579 // We will only allow preferred activities that came
1580 // from the same match quality.
1581 int match = 0;
1582 final int N = query.size();
1583 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1584 for (int j=0; j<N; j++) {
1585 ResolveInfo ri = query.get(j);
1586 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1587 + ": 0x" + Integer.toHexString(match));
1588 if (ri.match > match) match = ri.match;
1589 }
1590 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1591 + Integer.toHexString(match));
1592 match &= IntentFilter.MATCH_CATEGORY_MASK;
1593 final int M = prefs.size();
1594 for (int i=0; i<M; i++) {
1595 PreferredActivity pa = prefs.get(i);
1596 if (pa.mMatch != match) {
1597 continue;
1598 }
1599 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1600 if (DEBUG_PREFERRED) {
1601 Log.v(TAG, "Got preferred activity:");
1602 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1603 }
1604 if (ai != null) {
1605 for (int j=0; j<N; j++) {
1606 ResolveInfo ri = query.get(j);
1607 if (!ri.activityInfo.applicationInfo.packageName
1608 .equals(ai.applicationInfo.packageName)) {
1609 continue;
1610 }
1611 if (!ri.activityInfo.name.equals(ai.name)) {
1612 continue;
1613 }
1614
1615 // Okay we found a previously set preferred app.
1616 // If the result set is different from when this
1617 // was created, we need to clear it and re-ask the
1618 // user their preference.
1619 if (!pa.sameSet(query, priority)) {
1620 Log.i(TAG, "Result set changed, dropping preferred activity for "
1621 + intent + " type " + resolvedType);
1622 mSettings.mPreferredActivities.removeFilter(pa);
1623 return null;
1624 }
1625
1626 // Yay!
1627 return ri;
1628 }
1629 }
1630 }
1631 }
1632 }
1633 return null;
1634 }
1635
1636 public List<ResolveInfo> queryIntentActivities(Intent intent,
1637 String resolvedType, int flags) {
1638 ComponentName comp = intent.getComponent();
1639 if (comp != null) {
1640 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1641 ActivityInfo ai = getActivityInfo(comp, flags);
1642 if (ai != null) {
1643 ResolveInfo ri = new ResolveInfo();
1644 ri.activityInfo = ai;
1645 list.add(ri);
1646 }
1647 return list;
1648 }
1649
1650 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001651 String pkgName = intent.getPackage();
1652 if (pkgName == null) {
1653 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1654 resolvedType, flags);
1655 }
1656 PackageParser.Package pkg = mPackages.get(pkgName);
1657 if (pkg != null) {
1658 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1659 resolvedType, flags, pkg.activities);
1660 }
1661 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 }
1663 }
1664
1665 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1666 Intent[] specifics, String[] specificTypes, Intent intent,
1667 String resolvedType, int flags) {
1668 final String resultsAction = intent.getAction();
1669
1670 List<ResolveInfo> results = queryIntentActivities(
1671 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1672 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1673
1674 int specificsPos = 0;
1675 int N;
1676
1677 // todo: note that the algorithm used here is O(N^2). This
1678 // isn't a problem in our current environment, but if we start running
1679 // into situations where we have more than 5 or 10 matches then this
1680 // should probably be changed to something smarter...
1681
1682 // First we go through and resolve each of the specific items
1683 // that were supplied, taking care of removing any corresponding
1684 // duplicate items in the generic resolve list.
1685 if (specifics != null) {
1686 for (int i=0; i<specifics.length; i++) {
1687 final Intent sintent = specifics[i];
1688 if (sintent == null) {
1689 continue;
1690 }
1691
1692 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1693 String action = sintent.getAction();
1694 if (resultsAction != null && resultsAction.equals(action)) {
1695 // If this action was explicitly requested, then don't
1696 // remove things that have it.
1697 action = null;
1698 }
1699 ComponentName comp = sintent.getComponent();
1700 ResolveInfo ri = null;
1701 ActivityInfo ai = null;
1702 if (comp == null) {
1703 ri = resolveIntent(
1704 sintent,
1705 specificTypes != null ? specificTypes[i] : null,
1706 flags);
1707 if (ri == null) {
1708 continue;
1709 }
1710 if (ri == mResolveInfo) {
1711 // ACK! Must do something better with this.
1712 }
1713 ai = ri.activityInfo;
1714 comp = new ComponentName(ai.applicationInfo.packageName,
1715 ai.name);
1716 } else {
1717 ai = getActivityInfo(comp, flags);
1718 if (ai == null) {
1719 continue;
1720 }
1721 }
1722
1723 // Look for any generic query activities that are duplicates
1724 // of this specific one, and remove them from the results.
1725 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1726 N = results.size();
1727 int j;
1728 for (j=specificsPos; j<N; j++) {
1729 ResolveInfo sri = results.get(j);
1730 if ((sri.activityInfo.name.equals(comp.getClassName())
1731 && sri.activityInfo.applicationInfo.packageName.equals(
1732 comp.getPackageName()))
1733 || (action != null && sri.filter.matchAction(action))) {
1734 results.remove(j);
1735 if (Config.LOGV) Log.v(
1736 TAG, "Removing duplicate item from " + j
1737 + " due to specific " + specificsPos);
1738 if (ri == null) {
1739 ri = sri;
1740 }
1741 j--;
1742 N--;
1743 }
1744 }
1745
1746 // Add this specific item to its proper place.
1747 if (ri == null) {
1748 ri = new ResolveInfo();
1749 ri.activityInfo = ai;
1750 }
1751 results.add(specificsPos, ri);
1752 ri.specificIndex = i;
1753 specificsPos++;
1754 }
1755 }
1756
1757 // Now we go through the remaining generic results and remove any
1758 // duplicate actions that are found here.
1759 N = results.size();
1760 for (int i=specificsPos; i<N-1; i++) {
1761 final ResolveInfo rii = results.get(i);
1762 if (rii.filter == null) {
1763 continue;
1764 }
1765
1766 // Iterate over all of the actions of this result's intent
1767 // filter... typically this should be just one.
1768 final Iterator<String> it = rii.filter.actionsIterator();
1769 if (it == null) {
1770 continue;
1771 }
1772 while (it.hasNext()) {
1773 final String action = it.next();
1774 if (resultsAction != null && resultsAction.equals(action)) {
1775 // If this action was explicitly requested, then don't
1776 // remove things that have it.
1777 continue;
1778 }
1779 for (int j=i+1; j<N; j++) {
1780 final ResolveInfo rij = results.get(j);
1781 if (rij.filter != null && rij.filter.hasAction(action)) {
1782 results.remove(j);
1783 if (Config.LOGV) Log.v(
1784 TAG, "Removing duplicate item from " + j
1785 + " due to action " + action + " at " + i);
1786 j--;
1787 N--;
1788 }
1789 }
1790 }
1791
1792 // If the caller didn't request filter information, drop it now
1793 // so we don't have to marshall/unmarshall it.
1794 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1795 rii.filter = null;
1796 }
1797 }
1798
1799 // Filter out the caller activity if so requested.
1800 if (caller != null) {
1801 N = results.size();
1802 for (int i=0; i<N; i++) {
1803 ActivityInfo ainfo = results.get(i).activityInfo;
1804 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1805 && caller.getClassName().equals(ainfo.name)) {
1806 results.remove(i);
1807 break;
1808 }
1809 }
1810 }
1811
1812 // If the caller didn't request filter information,
1813 // drop them now so we don't have to
1814 // marshall/unmarshall it.
1815 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1816 N = results.size();
1817 for (int i=0; i<N; i++) {
1818 results.get(i).filter = null;
1819 }
1820 }
1821
1822 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1823 return results;
1824 }
1825
1826 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1827 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001828 ComponentName comp = intent.getComponent();
1829 if (comp != null) {
1830 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1831 ActivityInfo ai = getReceiverInfo(comp, flags);
1832 if (ai != null) {
1833 ResolveInfo ri = new ResolveInfo();
1834 ri.activityInfo = ai;
1835 list.add(ri);
1836 }
1837 return list;
1838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001841 String pkgName = intent.getPackage();
1842 if (pkgName == null) {
1843 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1844 resolvedType, flags);
1845 }
1846 PackageParser.Package pkg = mPackages.get(pkgName);
1847 if (pkg != null) {
1848 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1849 resolvedType, flags, pkg.receivers);
1850 }
1851 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853 }
1854
1855 public ResolveInfo resolveService(Intent intent, String resolvedType,
1856 int flags) {
1857 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1858 flags);
1859 if (query != null) {
1860 if (query.size() >= 1) {
1861 // If there is more than one service with the same priority,
1862 // just arbitrarily pick the first one.
1863 return query.get(0);
1864 }
1865 }
1866 return null;
1867 }
1868
1869 public List<ResolveInfo> queryIntentServices(Intent intent,
1870 String resolvedType, int flags) {
1871 ComponentName comp = intent.getComponent();
1872 if (comp != null) {
1873 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1874 ServiceInfo si = getServiceInfo(comp, flags);
1875 if (si != null) {
1876 ResolveInfo ri = new ResolveInfo();
1877 ri.serviceInfo = si;
1878 list.add(ri);
1879 }
1880 return list;
1881 }
1882
1883 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001884 String pkgName = intent.getPackage();
1885 if (pkgName == null) {
1886 return (List<ResolveInfo>)mServices.queryIntent(intent,
1887 resolvedType, flags);
1888 }
1889 PackageParser.Package pkg = mPackages.get(pkgName);
1890 if (pkg != null) {
1891 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1892 resolvedType, flags, pkg.services);
1893 }
1894 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
1896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 public List<PackageInfo> getInstalledPackages(int flags) {
1899 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1900
1901 synchronized (mPackages) {
1902 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1903 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1904 while (i.hasNext()) {
1905 final PackageSetting ps = i.next();
1906 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1907 if(psPkg != null) {
1908 finalList.add(psPkg);
1909 }
1910 }
1911 }
1912 else {
1913 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1914 while (i.hasNext()) {
1915 final PackageParser.Package p = i.next();
1916 if (p.applicationInfo != null) {
1917 PackageInfo pi = generatePackageInfo(p, flags);
1918 if(pi != null) {
1919 finalList.add(pi);
1920 }
1921 }
1922 }
1923 }
1924 }
1925 return finalList;
1926 }
1927
1928 public List<ApplicationInfo> getInstalledApplications(int flags) {
1929 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1930 synchronized(mPackages) {
1931 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1932 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1933 while (i.hasNext()) {
1934 final PackageSetting ps = i.next();
1935 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1936 if(ai != null) {
1937 finalList.add(ai);
1938 }
1939 }
1940 }
1941 else {
1942 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1943 while (i.hasNext()) {
1944 final PackageParser.Package p = i.next();
1945 if (p.applicationInfo != null) {
1946 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1947 if(ai != null) {
1948 finalList.add(ai);
1949 }
1950 }
1951 }
1952 }
1953 }
1954 return finalList;
1955 }
1956
1957 public List<ApplicationInfo> getPersistentApplications(int flags) {
1958 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1959
1960 synchronized (mPackages) {
1961 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1962 while (i.hasNext()) {
1963 PackageParser.Package p = i.next();
1964 if (p.applicationInfo != null
1965 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1966 && (!mSafeMode || (p.applicationInfo.flags
1967 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1968 finalList.add(p.applicationInfo);
1969 }
1970 }
1971 }
1972
1973 return finalList;
1974 }
1975
1976 public ProviderInfo resolveContentProvider(String name, int flags) {
1977 synchronized (mPackages) {
1978 final PackageParser.Provider provider = mProviders.get(name);
1979 return provider != null
1980 && mSettings.isEnabledLP(provider.info, flags)
1981 && (!mSafeMode || (provider.info.applicationInfo.flags
1982 &ApplicationInfo.FLAG_SYSTEM) != 0)
1983 ? PackageParser.generateProviderInfo(provider, flags)
1984 : null;
1985 }
1986 }
1987
Fred Quintana718d8a22009-04-29 17:53:20 -07001988 /**
1989 * @deprecated
1990 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 public void querySyncProviders(List outNames, List outInfo) {
1992 synchronized (mPackages) {
1993 Iterator<Map.Entry<String, PackageParser.Provider>> i
1994 = mProviders.entrySet().iterator();
1995
1996 while (i.hasNext()) {
1997 Map.Entry<String, PackageParser.Provider> entry = i.next();
1998 PackageParser.Provider p = entry.getValue();
1999
2000 if (p.syncable
2001 && (!mSafeMode || (p.info.applicationInfo.flags
2002 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2003 outNames.add(entry.getKey());
2004 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2005 }
2006 }
2007 }
2008 }
2009
2010 public List<ProviderInfo> queryContentProviders(String processName,
2011 int uid, int flags) {
2012 ArrayList<ProviderInfo> finalList = null;
2013
2014 synchronized (mPackages) {
2015 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2016 while (i.hasNext()) {
2017 PackageParser.Provider p = i.next();
2018 if (p.info.authority != null
2019 && (processName == null ||
2020 (p.info.processName.equals(processName)
2021 && p.info.applicationInfo.uid == uid))
2022 && mSettings.isEnabledLP(p.info, flags)
2023 && (!mSafeMode || (p.info.applicationInfo.flags
2024 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2025 if (finalList == null) {
2026 finalList = new ArrayList<ProviderInfo>(3);
2027 }
2028 finalList.add(PackageParser.generateProviderInfo(p,
2029 flags));
2030 }
2031 }
2032 }
2033
2034 if (finalList != null) {
2035 Collections.sort(finalList, mProviderInitOrderSorter);
2036 }
2037
2038 return finalList;
2039 }
2040
2041 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2042 int flags) {
2043 synchronized (mPackages) {
2044 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2045 return PackageParser.generateInstrumentationInfo(i, flags);
2046 }
2047 }
2048
2049 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2050 int flags) {
2051 ArrayList<InstrumentationInfo> finalList =
2052 new ArrayList<InstrumentationInfo>();
2053
2054 synchronized (mPackages) {
2055 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2056 while (i.hasNext()) {
2057 PackageParser.Instrumentation p = i.next();
2058 if (targetPackage == null
2059 || targetPackage.equals(p.info.targetPackage)) {
2060 finalList.add(PackageParser.generateInstrumentationInfo(p,
2061 flags));
2062 }
2063 }
2064 }
2065
2066 return finalList;
2067 }
2068
2069 private void scanDirLI(File dir, int flags, int scanMode) {
2070 Log.d(TAG, "Scanning app dir " + dir);
2071
2072 String[] files = dir.list();
2073
2074 int i;
2075 for (i=0; i<files.length; i++) {
2076 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002077 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
2079 }
2080 }
2081
2082 private static void reportSettingsProblem(int priority, String msg) {
2083 try {
2084 File dataDir = Environment.getDataDirectory();
2085 File systemDir = new File(dataDir, "system");
2086 File fname = new File(systemDir, "uiderrors.txt");
2087 FileOutputStream out = new FileOutputStream(fname, true);
2088 PrintWriter pw = new PrintWriter(out);
2089 pw.println(msg);
2090 pw.close();
2091 FileUtils.setPermissions(
2092 fname.toString(),
2093 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2094 -1, -1);
2095 } catch (java.io.IOException e) {
2096 }
2097 Log.println(priority, TAG, msg);
2098 }
2099
2100 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2101 PackageParser.Package pkg, File srcFile, int parseFlags) {
2102 if (GET_CERTIFICATES) {
2103 if (ps == null || !ps.codePath.equals(srcFile)
2104 || ps.getTimeStamp() != srcFile.lastModified()) {
2105 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2106 if (!pp.collectCertificates(pkg, parseFlags)) {
2107 mLastScanError = pp.getParseError();
2108 return false;
2109 }
2110 }
2111 }
2112 return true;
2113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 /*
2116 * Scan a package and return the newly parsed package.
2117 * Returns null in case of errors and the error code is stored in mLastScanError
2118 */
2119 private PackageParser.Package scanPackageLI(File scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002120 int parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 int scanMode) {
2122 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002123 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002125 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002128 scanPath,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002129 mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 if (pkg == null) {
2131 mLastScanError = pp.getParseError();
2132 return null;
2133 }
2134 PackageSetting ps;
2135 PackageSetting updatedPkg;
2136 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002137 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2139 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002140 // Verify certificates first
2141 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2142 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2143 return null;
2144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 if (updatedPkg != null) {
2146 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2147 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2148 }
2149 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2150 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002151 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2152 if (pkg.mVersionCode < ps.versionCode) {
2153 // The system package has been updated and the code path does not match
2154 // Ignore entry. Just return
2155 Log.w(TAG, "Package:" + pkg.packageName +
2156 " has been updated. Ignoring the one from path:"+scanFile);
2157 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2158 return null;
2159 } else {
2160 // Delete the older apk pointed to by ps
2161 // At this point, its safely assumed that package installation for
2162 // apps in system partition will go through. If not there won't be a working
2163 // version of the app
2164 synchronized (mPackages) {
2165 // Just remove the loaded entries from package lists.
2166 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002167 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002168 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2169 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002170 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 }
2173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 // The apk is forward locked (not public) if its code and resources
2175 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002176 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002178 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002179 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002180
2181 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2182 if (ps != null && ps.resourcePathString != null) {
2183 pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2184 } else {
2185 // Should not happen at all. Just log an error.
2186 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2187 }
2188 } else {
2189 pkg.applicationInfo.publicSourceDir = pkg.mScanPath;
2190 }
2191 pkg.applicationInfo.sourceDir = pkg.mScanPath;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002193 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 }
2195
2196 private static String fixProcessName(String defProcessName,
2197 String processName, int uid) {
2198 if (processName == null) {
2199 return defProcessName;
2200 }
2201 return processName;
2202 }
2203
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002204 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2206 if (pkg.mSignatures != null) {
2207 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2208 updateSignature)) {
2209 Log.e(TAG, "Package " + pkg.packageName
2210 + " signatures do not match the previously installed version; ignoring!");
2211 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2212 return false;
2213 }
2214
2215 if (pkgSetting.sharedUser != null) {
2216 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2217 pkg.mSignatures, updateSignature)) {
2218 Log.e(TAG, "Package " + pkg.packageName
2219 + " has no signatures that match those in shared user "
2220 + pkgSetting.sharedUser.name + "; ignoring!");
2221 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2222 return false;
2223 }
2224 }
2225 } else {
2226 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2227 }
2228 return true;
2229 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002230
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002231 public boolean performDexOpt(String packageName) {
2232 if (!mNoDexOpt) {
2233 return false;
2234 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002235
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002236 PackageParser.Package p;
2237 synchronized (mPackages) {
2238 p = mPackages.get(packageName);
2239 if (p == null || p.mDidDexOpt) {
2240 return false;
2241 }
2242 }
2243 synchronized (mInstallLock) {
2244 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2245 }
2246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002247
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002248 static final int DEX_OPT_SKIPPED = 0;
2249 static final int DEX_OPT_PERFORMED = 1;
2250 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002251
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002252 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2253 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002254 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002255 String path = pkg.mScanPath;
2256 int ret = 0;
2257 try {
2258 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002259 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002260 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002261 pkg.mDidDexOpt = true;
2262 performed = true;
2263 }
2264 } catch (FileNotFoundException e) {
2265 Log.w(TAG, "Apk not found for dexopt: " + path);
2266 ret = -1;
2267 } catch (IOException e) {
2268 Log.w(TAG, "Exception reading apk: " + path, e);
2269 ret = -1;
2270 }
2271 if (ret < 0) {
2272 //error from installer
2273 return DEX_OPT_FAILED;
2274 }
2275 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002276
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002277 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2278 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002279
2280 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2281 return Environment.isEncryptedFilesystemEnabled() &&
2282 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2283 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285 private PackageParser.Package scanPackageLI(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 PackageParser.Package pkg, int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002287 File scanFile = new File(pkg.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 mScanningPath = scanFile;
2289 if (pkg == null) {
2290 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2291 return null;
2292 }
2293
2294 final String pkgName = pkg.applicationInfo.packageName;
2295 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2296 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2297 }
2298
2299 if (pkgName.equals("android")) {
2300 synchronized (mPackages) {
2301 if (mAndroidApplication != null) {
2302 Log.w(TAG, "*************************************************");
2303 Log.w(TAG, "Core android package being redefined. Skipping.");
2304 Log.w(TAG, " file=" + mScanningPath);
2305 Log.w(TAG, "*************************************************");
2306 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2307 return null;
2308 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 // Set up information for our fall-back user intent resolution
2311 // activity.
2312 mPlatformPackage = pkg;
2313 pkg.mVersionCode = mSdkVersion;
2314 mAndroidApplication = pkg.applicationInfo;
2315 mResolveActivity.applicationInfo = mAndroidApplication;
2316 mResolveActivity.name = ResolverActivity.class.getName();
2317 mResolveActivity.packageName = mAndroidApplication.packageName;
2318 mResolveActivity.processName = mAndroidApplication.processName;
2319 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2320 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2321 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2322 mResolveActivity.exported = true;
2323 mResolveActivity.enabled = true;
2324 mResolveInfo.activityInfo = mResolveActivity;
2325 mResolveInfo.priority = 0;
2326 mResolveInfo.preferredOrder = 0;
2327 mResolveInfo.match = 0;
2328 mResolveComponentName = new ComponentName(
2329 mAndroidApplication.packageName, mResolveActivity.name);
2330 }
2331 }
2332
2333 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2334 TAG, "Scanning package " + pkgName);
2335 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2336 Log.w(TAG, "*************************************************");
2337 Log.w(TAG, "Application package " + pkgName
2338 + " already installed. Skipping duplicate.");
2339 Log.w(TAG, "*************************************************");
2340 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2341 return null;
2342 }
2343
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002344 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002345 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2346 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 SharedUserSetting suid = null;
2349 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 synchronized (mPackages) {
2354 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002355 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2356 if (mTmpSharedLibraries == null ||
2357 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2358 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2359 }
2360 int num = 0;
2361 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2362 for (int i=0; i<N; i++) {
2363 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 if (file == null) {
2365 Log.e(TAG, "Package " + pkg.packageName
2366 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002367 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2369 return null;
2370 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002371 mTmpSharedLibraries[num] = file;
2372 num++;
2373 }
2374 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2375 for (int i=0; i<N; i++) {
2376 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2377 if (file == null) {
2378 Log.w(TAG, "Package " + pkg.packageName
2379 + " desires unavailable shared library "
2380 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2381 } else {
2382 mTmpSharedLibraries[num] = file;
2383 num++;
2384 }
2385 }
2386 if (num > 0) {
2387 pkg.usesLibraryFiles = new String[num];
2388 System.arraycopy(mTmpSharedLibraries, 0,
2389 pkg.usesLibraryFiles, 0, num);
2390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002391
Dianne Hackborn49237342009-08-27 20:08:01 -07002392 if (pkg.reqFeatures != null) {
2393 N = pkg.reqFeatures.size();
2394 for (int i=0; i<N; i++) {
2395 FeatureInfo fi = pkg.reqFeatures.get(i);
2396 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2397 // Don't care.
2398 continue;
2399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002400
Dianne Hackborn49237342009-08-27 20:08:01 -07002401 if (fi.name != null) {
2402 if (mAvailableFeatures.get(fi.name) == null) {
2403 Log.e(TAG, "Package " + pkg.packageName
2404 + " requires unavailable feature "
2405 + fi.name + "; failing!");
2406 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2407 return null;
2408 }
2409 }
2410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 }
2412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 if (pkg.mSharedUserId != null) {
2415 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2416 pkg.applicationInfo.flags, true);
2417 if (suid == null) {
2418 Log.w(TAG, "Creating application package " + pkgName
2419 + " for shared user failed");
2420 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2421 return null;
2422 }
2423 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2424 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2425 + suid.userId + "): packages=" + suid.packages);
2426 }
2427 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002428
2429 // Just create the setting, don't add it yet. For already existing packages
2430 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2432 destResourceFile, pkg.applicationInfo.flags, true, false);
2433 if (pkgSetting == null) {
2434 Log.w(TAG, "Creating application package " + pkgName + " failed");
2435 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2436 return null;
2437 }
2438 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2439 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 pkg.applicationInfo.uid = pkgSetting.userId;
2443 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002444
2445 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2447 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2448 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2449 return null;
2450 }
2451 // The signature has changed, but this package is in the system
2452 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002453 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 // However... if this package is part of a shared user, but it
2455 // doesn't match the signature of the shared user, let's fail.
2456 // What this means is that you can't change the signatures
2457 // associated with an overall shared user, which doesn't seem all
2458 // that unreasonable.
2459 if (pkgSetting.sharedUser != null) {
2460 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2461 pkg.mSignatures, false)) {
2462 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2463 return null;
2464 }
2465 }
2466 removeExisting = true;
2467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002468
The Android Open Source Project10592532009-03-18 17:39:46 -07002469 // Verify that this new package doesn't have any content providers
2470 // that conflict with existing packages. Only do this if the
2471 // package isn't already installed, since we don't want to break
2472 // things that are installed.
2473 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2474 int N = pkg.providers.size();
2475 int i;
2476 for (i=0; i<N; i++) {
2477 PackageParser.Provider p = pkg.providers.get(i);
2478 String names[] = p.info.authority.split(";");
2479 for (int j = 0; j < names.length; j++) {
2480 if (mProviders.containsKey(names[j])) {
2481 PackageParser.Provider other = mProviders.get(names[j]);
2482 Log.w(TAG, "Can't install because provider name " + names[j] +
2483 " (in package " + pkg.applicationInfo.packageName +
2484 ") is already used by "
2485 + ((other != null && other.component != null)
2486 ? other.component.getPackageName() : "?"));
2487 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2488 return null;
2489 }
2490 }
2491 }
2492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 }
2494
2495 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002496 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002498 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 if (ret != 0) {
2500 String msg = "System package " + pkg.packageName
2501 + " could not have data directory erased after signature change.";
2502 reportSettingsProblem(Log.WARN, msg);
2503 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2504 return null;
2505 }
2506 }
2507 Log.w(TAG, "System package " + pkg.packageName
2508 + " signature changed: existing data removed.");
2509 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 long scanFileTime = scanFile.lastModified();
2513 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2514 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2515 pkg.applicationInfo.processName = fixProcessName(
2516 pkg.applicationInfo.packageName,
2517 pkg.applicationInfo.processName,
2518 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519
2520 File dataPath;
2521 if (mPlatformPackage == pkg) {
2522 // The system package is special.
2523 dataPath = new File (Environment.getDataDirectory(), "system");
2524 pkg.applicationInfo.dataDir = dataPath.getPath();
2525 } else {
2526 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002527 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2528 if (useEncryptedFSDir) {
2529 dataPath = new File(mSecureAppDataDir, pkgName);
2530 } else {
2531 dataPath = new File(mAppDataDir, pkgName);
2532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 if (dataPath.exists()) {
2534 mOutPermissions[1] = 0;
2535 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2536 if (mOutPermissions[1] == pkg.applicationInfo.uid
2537 || !Process.supportsProcesses()) {
2538 pkg.applicationInfo.dataDir = dataPath.getPath();
2539 } else {
2540 boolean recovered = false;
2541 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2542 // If this is a system app, we can at least delete its
2543 // current data so the application will still work.
2544 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002545 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 if(ret >= 0) {
2547 // Old data gone!
2548 String msg = "System package " + pkg.packageName
2549 + " has changed from uid: "
2550 + mOutPermissions[1] + " to "
2551 + pkg.applicationInfo.uid + "; old data erased";
2552 reportSettingsProblem(Log.WARN, msg);
2553 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002556 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 pkg.applicationInfo.uid);
2558 if (ret == -1) {
2559 // Ack should not happen!
2560 msg = "System package " + pkg.packageName
2561 + " could not have data directory re-created after delete.";
2562 reportSettingsProblem(Log.WARN, msg);
2563 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2564 return null;
2565 }
2566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 if (!recovered) {
2569 mHasSystemUidErrors = true;
2570 }
2571 }
2572 if (!recovered) {
2573 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2574 + pkg.applicationInfo.uid + "/fs_"
2575 + mOutPermissions[1];
2576 String msg = "Package " + pkg.packageName
2577 + " has mismatched uid: "
2578 + mOutPermissions[1] + " on disk, "
2579 + pkg.applicationInfo.uid + " in settings";
2580 synchronized (mPackages) {
2581 if (!mReportedUidError) {
2582 mReportedUidError = true;
2583 msg = msg + "; read messages:\n"
2584 + mSettings.getReadMessagesLP();
2585 }
2586 reportSettingsProblem(Log.ERROR, msg);
2587 }
2588 }
2589 }
2590 pkg.applicationInfo.dataDir = dataPath.getPath();
2591 } else {
2592 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2593 Log.v(TAG, "Want this data dir: " + dataPath);
2594 //invoke installer to do the actual installation
2595 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002596 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 pkg.applicationInfo.uid);
2598 if(ret < 0) {
2599 // Error from installer
2600 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2601 return null;
2602 }
2603 } else {
2604 dataPath.mkdirs();
2605 if (dataPath.exists()) {
2606 FileUtils.setPermissions(
2607 dataPath.toString(),
2608 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2609 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2610 }
2611 }
2612 if (dataPath.exists()) {
2613 pkg.applicationInfo.dataDir = dataPath.getPath();
2614 } else {
2615 Log.w(TAG, "Unable to create data directory: " + dataPath);
2616 pkg.applicationInfo.dataDir = null;
2617 }
2618 }
2619 }
2620
2621 // Perform shared library installation and dex validation and
2622 // optimization, if this is not a system app.
2623 if (mInstaller != null) {
2624 String path = scanFile.getPath();
2625 if (scanFileNewer) {
2626 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002627 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2628 if (err != PackageManager.INSTALL_SUCCEEDED) {
2629 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 return null;
2631 }
2632 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002633 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002634
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002635 if ((scanMode&SCAN_NO_DEX) == 0) {
2636 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2638 return null;
2639 }
2640 }
2641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 if (mFactoryTest && pkg.requestedPermissions.contains(
2644 android.Manifest.permission.FACTORY_TEST)) {
2645 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2646 }
2647
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002648 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 mAppDirs.put(pkg.mPath, pkg);
2651 }
2652
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002653 // Request the ActivityManager to kill the process(only for existing packages)
2654 // so that we do not end up in a confused state while the user is still using the older
2655 // version of the application while the new one gets installed.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002656 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0) {
2657 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002658 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002659 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002665 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 int N = pkg.providers.size();
2667 StringBuilder r = null;
2668 int i;
2669 for (i=0; i<N; i++) {
2670 PackageParser.Provider p = pkg.providers.get(i);
2671 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2672 p.info.processName, pkg.applicationInfo.uid);
2673 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2674 p.info.name), p);
2675 p.syncable = p.info.isSyncable;
2676 String names[] = p.info.authority.split(";");
2677 p.info.authority = null;
2678 for (int j = 0; j < names.length; j++) {
2679 if (j == 1 && p.syncable) {
2680 // We only want the first authority for a provider to possibly be
2681 // syncable, so if we already added this provider using a different
2682 // authority clear the syncable flag. We copy the provider before
2683 // changing it because the mProviders object contains a reference
2684 // to a provider that we don't want to change.
2685 // Only do this for the second authority since the resulting provider
2686 // object can be the same for all future authorities for this provider.
2687 p = new PackageParser.Provider(p);
2688 p.syncable = false;
2689 }
2690 if (!mProviders.containsKey(names[j])) {
2691 mProviders.put(names[j], p);
2692 if (p.info.authority == null) {
2693 p.info.authority = names[j];
2694 } else {
2695 p.info.authority = p.info.authority + ";" + names[j];
2696 }
2697 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2698 Log.d(TAG, "Registered content provider: " + names[j] +
2699 ", className = " + p.info.name +
2700 ", isSyncable = " + p.info.isSyncable);
2701 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002702 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 Log.w(TAG, "Skipping provider name " + names[j] +
2704 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002705 "): name already used by "
2706 + ((other != null && other.component != null)
2707 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 }
2709 }
2710 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2711 if (r == null) {
2712 r = new StringBuilder(256);
2713 } else {
2714 r.append(' ');
2715 }
2716 r.append(p.info.name);
2717 }
2718 }
2719 if (r != null) {
2720 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 N = pkg.services.size();
2724 r = null;
2725 for (i=0; i<N; i++) {
2726 PackageParser.Service s = pkg.services.get(i);
2727 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2728 s.info.processName, pkg.applicationInfo.uid);
2729 mServices.addService(s);
2730 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2731 if (r == null) {
2732 r = new StringBuilder(256);
2733 } else {
2734 r.append(' ');
2735 }
2736 r.append(s.info.name);
2737 }
2738 }
2739 if (r != null) {
2740 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2741 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 N = pkg.receivers.size();
2744 r = null;
2745 for (i=0; i<N; i++) {
2746 PackageParser.Activity a = pkg.receivers.get(i);
2747 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2748 a.info.processName, pkg.applicationInfo.uid);
2749 mReceivers.addActivity(a, "receiver");
2750 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2751 if (r == null) {
2752 r = new StringBuilder(256);
2753 } else {
2754 r.append(' ');
2755 }
2756 r.append(a.info.name);
2757 }
2758 }
2759 if (r != null) {
2760 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 N = pkg.activities.size();
2764 r = null;
2765 for (i=0; i<N; i++) {
2766 PackageParser.Activity a = pkg.activities.get(i);
2767 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2768 a.info.processName, pkg.applicationInfo.uid);
2769 mActivities.addActivity(a, "activity");
2770 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2771 if (r == null) {
2772 r = new StringBuilder(256);
2773 } else {
2774 r.append(' ');
2775 }
2776 r.append(a.info.name);
2777 }
2778 }
2779 if (r != null) {
2780 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 N = pkg.permissionGroups.size();
2784 r = null;
2785 for (i=0; i<N; i++) {
2786 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2787 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2788 if (cur == null) {
2789 mPermissionGroups.put(pg.info.name, pg);
2790 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2791 if (r == null) {
2792 r = new StringBuilder(256);
2793 } else {
2794 r.append(' ');
2795 }
2796 r.append(pg.info.name);
2797 }
2798 } else {
2799 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2800 + pg.info.packageName + " ignored: original from "
2801 + cur.info.packageName);
2802 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2803 if (r == null) {
2804 r = new StringBuilder(256);
2805 } else {
2806 r.append(' ');
2807 }
2808 r.append("DUP:");
2809 r.append(pg.info.name);
2810 }
2811 }
2812 }
2813 if (r != null) {
2814 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 N = pkg.permissions.size();
2818 r = null;
2819 for (i=0; i<N; i++) {
2820 PackageParser.Permission p = pkg.permissions.get(i);
2821 HashMap<String, BasePermission> permissionMap =
2822 p.tree ? mSettings.mPermissionTrees
2823 : mSettings.mPermissions;
2824 p.group = mPermissionGroups.get(p.info.group);
2825 if (p.info.group == null || p.group != null) {
2826 BasePermission bp = permissionMap.get(p.info.name);
2827 if (bp == null) {
2828 bp = new BasePermission(p.info.name, p.info.packageName,
2829 BasePermission.TYPE_NORMAL);
2830 permissionMap.put(p.info.name, bp);
2831 }
2832 if (bp.perm == null) {
2833 if (bp.sourcePackage == null
2834 || bp.sourcePackage.equals(p.info.packageName)) {
2835 BasePermission tree = findPermissionTreeLP(p.info.name);
2836 if (tree == null
2837 || tree.sourcePackage.equals(p.info.packageName)) {
2838 bp.perm = p;
2839 bp.uid = pkg.applicationInfo.uid;
2840 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2841 if (r == null) {
2842 r = new StringBuilder(256);
2843 } else {
2844 r.append(' ');
2845 }
2846 r.append(p.info.name);
2847 }
2848 } else {
2849 Log.w(TAG, "Permission " + p.info.name + " from package "
2850 + p.info.packageName + " ignored: base tree "
2851 + tree.name + " is from package "
2852 + tree.sourcePackage);
2853 }
2854 } else {
2855 Log.w(TAG, "Permission " + p.info.name + " from package "
2856 + p.info.packageName + " ignored: original from "
2857 + bp.sourcePackage);
2858 }
2859 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2860 if (r == null) {
2861 r = new StringBuilder(256);
2862 } else {
2863 r.append(' ');
2864 }
2865 r.append("DUP:");
2866 r.append(p.info.name);
2867 }
2868 } else {
2869 Log.w(TAG, "Permission " + p.info.name + " from package "
2870 + p.info.packageName + " ignored: no group "
2871 + p.group);
2872 }
2873 }
2874 if (r != null) {
2875 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2876 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 N = pkg.instrumentation.size();
2879 r = null;
2880 for (i=0; i<N; i++) {
2881 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2882 a.info.packageName = pkg.applicationInfo.packageName;
2883 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2884 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2885 a.info.dataDir = pkg.applicationInfo.dataDir;
2886 mInstrumentation.put(a.component, a);
2887 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2888 if (r == null) {
2889 r = new StringBuilder(256);
2890 } else {
2891 r.append(' ');
2892 }
2893 r.append(a.info.name);
2894 }
2895 }
2896 if (r != null) {
2897 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002899
Dianne Hackborn854060af2009-07-09 18:14:31 -07002900 if (pkg.protectedBroadcasts != null) {
2901 N = pkg.protectedBroadcasts.size();
2902 for (i=0; i<N; i++) {
2903 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2904 }
2905 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 pkgSetting.setTimeStamp(scanFileTime);
2908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 return pkg;
2911 }
2912
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002913 private void killApplication(String pkgName, int uid) {
2914 // Request the ActivityManager to kill the process(only for existing packages)
2915 // so that we do not end up in a confused state while the user is still using the older
2916 // version of the application while the new one gets installed.
2917 IActivityManager am = ActivityManagerNative.getDefault();
2918 if (am != null) {
2919 try {
2920 am.killApplicationWithUid(pkgName, uid);
2921 } catch (RemoteException e) {
2922 }
2923 }
2924 }
2925
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002926 // The following constants are returned by cachePackageSharedLibsForAbiLI
2927 // to indicate if native shared libraries were found in the package.
2928 // Values are:
2929 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
2930 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
2931 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
2932 // in package (and not installed)
2933 //
2934 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
2935 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
2936 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002938 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
2939 // and automatically copy them to /data/data/<appname>/lib if present.
2940 //
2941 // NOTE: this method may throw an IOException if the library cannot
2942 // be copied to its final destination, e.g. if there isn't enough
2943 // room left on the data partition, or a ZipException if the package
2944 // file is malformed.
2945 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08002946 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
2947 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002948 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2949 final String apkLib = "lib/";
2950 final int apkLibLen = apkLib.length();
2951 final int cpuAbiLen = cpuAbi.length();
2952 final String libPrefix = "lib";
2953 final int libPrefixLen = libPrefix.length();
2954 final String libSuffix = ".so";
2955 final int libSuffixLen = libSuffix.length();
2956 boolean hasNativeLibraries = false;
2957 boolean installedNativeLibraries = false;
2958
2959 // the minimum length of a valid native shared library of the form
2960 // lib/<something>/lib<name>.so.
2961 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
2962
2963 ZipFile zipFile = new ZipFile(scanFile);
2964 Enumeration<ZipEntry> entries =
2965 (Enumeration<ZipEntry>) zipFile.entries();
2966
2967 while (entries.hasMoreElements()) {
2968 ZipEntry entry = entries.nextElement();
2969 // skip directories
2970 if (entry.isDirectory()) {
2971 continue;
2972 }
2973 String entryName = entry.getName();
2974
2975 // check that the entry looks like lib/<something>/lib<name>.so
2976 // here, but don't check the ABI just yet.
2977 //
2978 // - must be sufficiently long
2979 // - must end with libSuffix, i.e. ".so"
2980 // - must start with apkLib, i.e. "lib/"
2981 if (entryName.length() < minEntryLen ||
2982 !entryName.endsWith(libSuffix) ||
2983 !entryName.startsWith(apkLib) ) {
2984 continue;
2985 }
2986
2987 // file name must start with libPrefix, i.e. "lib"
2988 int lastSlash = entryName.lastIndexOf('/');
2989
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002990 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08002991 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
2992 continue;
2993 }
2994
2995 hasNativeLibraries = true;
2996
2997 // check the cpuAbi now, between lib/ and /lib<name>.so
2998 //
2999 if (lastSlash != apkLibLen + cpuAbiLen ||
3000 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3001 continue;
3002
3003 // extract the library file name, ensure it doesn't contain
3004 // weird characters. we're guaranteed here that it doesn't contain
3005 // a directory separator though.
3006 String libFileName = entryName.substring(lastSlash+1);
3007 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3008 continue;
3009 }
3010
3011 installedNativeLibraries = true;
3012
3013 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3014 File.separator + libFileName;
3015 File sharedLibraryFile = new File(sharedLibraryFilePath);
3016 if (! sharedLibraryFile.exists() ||
3017 sharedLibraryFile.length() != entry.getSize() ||
3018 sharedLibraryFile.lastModified() != entry.getTime()) {
3019 if (Config.LOGD) {
3020 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003022 if (mInstaller == null) {
3023 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003024 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003025 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003026 sharedLibraryFile);
3027 }
3028 }
3029 if (!hasNativeLibraries)
3030 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3031
3032 if (!installedNativeLibraries)
3033 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3034
3035 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3036 }
3037
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003038 // Find the gdbserver executable program in a package at
3039 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3040 //
3041 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3042 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3043 //
3044 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3045 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3046 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3047 final String GDBSERVER = "gdbserver";
3048 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3049
3050 ZipFile zipFile = new ZipFile(scanFile);
3051 Enumeration<ZipEntry> entries =
3052 (Enumeration<ZipEntry>) zipFile.entries();
3053
3054 while (entries.hasMoreElements()) {
3055 ZipEntry entry = entries.nextElement();
3056 // skip directories
3057 if (entry.isDirectory()) {
3058 continue;
3059 }
3060 String entryName = entry.getName();
3061
3062 if (!entryName.equals(apkGdbServerPath)) {
3063 continue;
3064 }
3065
3066 String installGdbServerPath = installGdbServerDir.getPath() +
3067 "/" + GDBSERVER;
3068 File installGdbServerFile = new File(installGdbServerPath);
3069 if (! installGdbServerFile.exists() ||
3070 installGdbServerFile.length() != entry.getSize() ||
3071 installGdbServerFile.lastModified() != entry.getTime()) {
3072 if (Config.LOGD) {
3073 Log.d(TAG, "Caching gdbserver " + entry.getName());
3074 }
3075 if (mInstaller == null) {
3076 installGdbServerDir.mkdir();
3077 }
3078 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3079 installGdbServerFile);
3080 }
3081 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3082 }
3083 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3084 }
3085
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003086 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3087 // and copy them to /data/data/<appname>/lib.
3088 //
3089 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3090 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3091 // one if ro.product.cpu.abi2 is defined.
3092 //
3093 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3094 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003095 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003096 try {
3097 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3098
3099 // some architectures are capable of supporting several CPU ABIs
3100 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3101 // this is indicated by the definition of the ro.product.cpu.abi2
3102 // system property.
3103 //
3104 // only scan the package twice in case of ABI mismatch
3105 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003106 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003107 if (cpuAbi2 != null) {
3108 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003110
3111 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3112 Log.w(TAG,"Native ABI mismatch from package file");
3113 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003115
3116 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3117 cpuAbi = cpuAbi2;
3118 }
3119 }
3120
3121 // for debuggable packages, also extract gdbserver from lib/<abi>
3122 // into /data/data/<appname>/lib too.
3123 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3124 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3125 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3126 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3127 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003130 } catch (ZipException e) {
3131 Log.w(TAG, "Failed to extract data from package file", e);
3132 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003134 Log.w(TAG, "Failed to cache package shared libs", e);
3135 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003137 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 }
3139
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003140 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003142 File binaryDir,
3143 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003144 InputStream inputStream = zipFile.getInputStream(entry);
3145 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003146 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003148 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 // now need to be left as world readable and owned by the system.
3150 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3151 ! tempFile.setLastModified(entry.getTime()) ||
3152 FileUtils.setPermissions(tempFilePath,
3153 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003154 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003156 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 // Failed to properly write file.
3158 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003159 throw new IOException("Couldn't create cached binary "
3160 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 }
3162 } finally {
3163 inputStream.close();
3164 }
3165 }
3166
3167 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3168 if (chatty && Config.LOGD) Log.d(
3169 TAG, "Removing package " + pkg.applicationInfo.packageName );
3170
3171 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 mPackages.remove(pkg.applicationInfo.packageName);
3175 if (pkg.mPath != null) {
3176 mAppDirs.remove(pkg.mPath);
3177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 PackageSetting ps = (PackageSetting)pkg.mExtras;
3180 if (ps != null && ps.sharedUser != null) {
3181 // XXX don't do this until the data is removed.
3182 if (false) {
3183 ps.sharedUser.packages.remove(ps);
3184 if (ps.sharedUser.packages.size() == 0) {
3185 // Remove.
3186 }
3187 }
3188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 int N = pkg.providers.size();
3191 StringBuilder r = null;
3192 int i;
3193 for (i=0; i<N; i++) {
3194 PackageParser.Provider p = pkg.providers.get(i);
3195 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3196 p.info.name));
3197 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 /* The is another ContentProvider with this authority when
3200 * this app was installed so this authority is null,
3201 * Ignore it as we don't have to unregister the provider.
3202 */
3203 continue;
3204 }
3205 String names[] = p.info.authority.split(";");
3206 for (int j = 0; j < names.length; j++) {
3207 if (mProviders.get(names[j]) == p) {
3208 mProviders.remove(names[j]);
3209 if (chatty && Config.LOGD) Log.d(
3210 TAG, "Unregistered content provider: " + names[j] +
3211 ", className = " + p.info.name +
3212 ", isSyncable = " + p.info.isSyncable);
3213 }
3214 }
3215 if (chatty) {
3216 if (r == null) {
3217 r = new StringBuilder(256);
3218 } else {
3219 r.append(' ');
3220 }
3221 r.append(p.info.name);
3222 }
3223 }
3224 if (r != null) {
3225 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3226 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 N = pkg.services.size();
3229 r = null;
3230 for (i=0; i<N; i++) {
3231 PackageParser.Service s = pkg.services.get(i);
3232 mServices.removeService(s);
3233 if (chatty) {
3234 if (r == null) {
3235 r = new StringBuilder(256);
3236 } else {
3237 r.append(' ');
3238 }
3239 r.append(s.info.name);
3240 }
3241 }
3242 if (r != null) {
3243 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 N = pkg.receivers.size();
3247 r = null;
3248 for (i=0; i<N; i++) {
3249 PackageParser.Activity a = pkg.receivers.get(i);
3250 mReceivers.removeActivity(a, "receiver");
3251 if (chatty) {
3252 if (r == null) {
3253 r = new StringBuilder(256);
3254 } else {
3255 r.append(' ');
3256 }
3257 r.append(a.info.name);
3258 }
3259 }
3260 if (r != null) {
3261 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3262 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 N = pkg.activities.size();
3265 r = null;
3266 for (i=0; i<N; i++) {
3267 PackageParser.Activity a = pkg.activities.get(i);
3268 mActivities.removeActivity(a, "activity");
3269 if (chatty) {
3270 if (r == null) {
3271 r = new StringBuilder(256);
3272 } else {
3273 r.append(' ');
3274 }
3275 r.append(a.info.name);
3276 }
3277 }
3278 if (r != null) {
3279 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 N = pkg.permissions.size();
3283 r = null;
3284 for (i=0; i<N; i++) {
3285 PackageParser.Permission p = pkg.permissions.get(i);
3286 boolean tree = false;
3287 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3288 if (bp == null) {
3289 tree = true;
3290 bp = mSettings.mPermissionTrees.get(p.info.name);
3291 }
3292 if (bp != null && bp.perm == p) {
3293 if (bp.type != BasePermission.TYPE_BUILTIN) {
3294 if (tree) {
3295 mSettings.mPermissionTrees.remove(p.info.name);
3296 } else {
3297 mSettings.mPermissions.remove(p.info.name);
3298 }
3299 } else {
3300 bp.perm = null;
3301 }
3302 if (chatty) {
3303 if (r == null) {
3304 r = new StringBuilder(256);
3305 } else {
3306 r.append(' ');
3307 }
3308 r.append(p.info.name);
3309 }
3310 }
3311 }
3312 if (r != null) {
3313 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 N = pkg.instrumentation.size();
3317 r = null;
3318 for (i=0; i<N; i++) {
3319 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3320 mInstrumentation.remove(a.component);
3321 if (chatty) {
3322 if (r == null) {
3323 r = new StringBuilder(256);
3324 } else {
3325 r.append(' ');
3326 }
3327 r.append(a.info.name);
3328 }
3329 }
3330 if (r != null) {
3331 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3332 }
3333 }
3334 }
3335
3336 private static final boolean isPackageFilename(String name) {
3337 return name != null && name.endsWith(".apk");
3338 }
3339
3340 private void updatePermissionsLP() {
3341 // Make sure there are no dangling permission trees.
3342 Iterator<BasePermission> it = mSettings.mPermissionTrees
3343 .values().iterator();
3344 while (it.hasNext()) {
3345 BasePermission bp = it.next();
3346 if (bp.perm == null) {
3347 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3348 + " from package " + bp.sourcePackage);
3349 it.remove();
3350 }
3351 }
3352
3353 // Make sure all dynamic permissions have been assigned to a package,
3354 // and make sure there are no dangling permissions.
3355 it = mSettings.mPermissions.values().iterator();
3356 while (it.hasNext()) {
3357 BasePermission bp = it.next();
3358 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3359 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3360 + bp.name + " pkg=" + bp.sourcePackage
3361 + " info=" + bp.pendingInfo);
3362 if (bp.perm == null && bp.pendingInfo != null) {
3363 BasePermission tree = findPermissionTreeLP(bp.name);
3364 if (tree != null) {
3365 bp.perm = new PackageParser.Permission(tree.perm.owner,
3366 new PermissionInfo(bp.pendingInfo));
3367 bp.perm.info.packageName = tree.perm.info.packageName;
3368 bp.perm.info.name = bp.name;
3369 bp.uid = tree.uid;
3370 }
3371 }
3372 }
3373 if (bp.perm == null) {
3374 Log.w(TAG, "Removing dangling permission: " + bp.name
3375 + " from package " + bp.sourcePackage);
3376 it.remove();
3377 }
3378 }
3379
3380 // Now update the permissions for all packages, in particular
3381 // replace the granted permissions of the system packages.
3382 for (PackageParser.Package pkg : mPackages.values()) {
3383 grantPermissionsLP(pkg, false);
3384 }
3385 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3388 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3389 if (ps == null) {
3390 return;
3391 }
3392 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3393 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 if (replace) {
3396 ps.permissionsFixed = false;
3397 if (gp == ps) {
3398 gp.grantedPermissions.clear();
3399 gp.gids = mGlobalGids;
3400 }
3401 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 if (gp.gids == null) {
3404 gp.gids = mGlobalGids;
3405 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 final int N = pkg.requestedPermissions.size();
3408 for (int i=0; i<N; i++) {
3409 String name = pkg.requestedPermissions.get(i);
3410 BasePermission bp = mSettings.mPermissions.get(name);
3411 PackageParser.Permission p = bp != null ? bp.perm : null;
3412 if (false) {
3413 if (gp != ps) {
3414 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3415 + ": " + p);
3416 }
3417 }
3418 if (p != null) {
3419 final String perm = p.info.name;
3420 boolean allowed;
3421 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3422 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3423 allowed = true;
3424 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3425 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003426 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003428 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 == PackageManager.SIGNATURE_MATCH);
3430 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3431 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3432 // For updated system applications, the signatureOrSystem permission
3433 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003434 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3436 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3437 if(sysPs.grantedPermissions.contains(perm)) {
3438 allowed = true;
3439 } else {
3440 allowed = false;
3441 }
3442 } else {
3443 allowed = true;
3444 }
3445 }
3446 }
3447 } else {
3448 allowed = false;
3449 }
3450 if (false) {
3451 if (gp != ps) {
3452 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3453 }
3454 }
3455 if (allowed) {
3456 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3457 && ps.permissionsFixed) {
3458 // If this is an existing, non-system package, then
3459 // we can't add any new permissions to it.
3460 if (!gp.loadedPermissions.contains(perm)) {
3461 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003462 // Except... if this is a permission that was added
3463 // to the platform (note: need to only do this when
3464 // updating the platform).
3465 final int NP = PackageParser.NEW_PERMISSIONS.length;
3466 for (int ip=0; ip<NP; ip++) {
3467 final PackageParser.NewPermissionInfo npi
3468 = PackageParser.NEW_PERMISSIONS[ip];
3469 if (npi.name.equals(perm)
3470 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3471 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003472 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003473 + pkg.packageName);
3474 break;
3475 }
3476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 }
3478 }
3479 if (allowed) {
3480 if (!gp.grantedPermissions.contains(perm)) {
3481 addedPermission = true;
3482 gp.grantedPermissions.add(perm);
3483 gp.gids = appendInts(gp.gids, bp.gids);
3484 }
3485 } else {
3486 Log.w(TAG, "Not granting permission " + perm
3487 + " to package " + pkg.packageName
3488 + " because it was previously installed without");
3489 }
3490 } else {
3491 Log.w(TAG, "Not granting permission " + perm
3492 + " to package " + pkg.packageName
3493 + " (protectionLevel=" + p.info.protectionLevel
3494 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3495 + ")");
3496 }
3497 } else {
3498 Log.w(TAG, "Unknown permission " + name
3499 + " in package " + pkg.packageName);
3500 }
3501 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003504 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3505 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 // This is the first that we have heard about this package, so the
3507 // permissions we have now selected are fixed until explicitly
3508 // changed.
3509 ps.permissionsFixed = true;
3510 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3511 }
3512 }
3513
3514 private final class ActivityIntentResolver
3515 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003516 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003517 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003518 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 }
3520
Mihai Preda074edef2009-05-18 17:13:31 +02003521 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003523 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3525 }
3526
Mihai Predaeae850c2009-05-13 10:13:48 +02003527 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3528 ArrayList<PackageParser.Activity> packageActivities) {
3529 if (packageActivities == null) {
3530 return null;
3531 }
3532 mFlags = flags;
3533 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3534 int N = packageActivities.size();
3535 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3536 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003537
3538 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003539 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003540 intentFilters = packageActivities.get(i).intents;
3541 if (intentFilters != null && intentFilters.size() > 0) {
3542 listCut.add(intentFilters);
3543 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003544 }
3545 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3546 }
3547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 public final void addActivity(PackageParser.Activity a, String type) {
3549 mActivities.put(a.component, a);
3550 if (SHOW_INFO || Config.LOGV) Log.v(
3551 TAG, " " + type + " " +
3552 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3553 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3554 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003555 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3557 if (SHOW_INFO || Config.LOGV) {
3558 Log.v(TAG, " IntentFilter:");
3559 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3560 }
3561 if (!intent.debugCheck()) {
3562 Log.w(TAG, "==> For Activity " + a.info.name);
3563 }
3564 addFilter(intent);
3565 }
3566 }
3567
3568 public final void removeActivity(PackageParser.Activity a, String type) {
3569 mActivities.remove(a.component);
3570 if (SHOW_INFO || Config.LOGV) Log.v(
3571 TAG, " " + type + " " +
3572 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3573 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3574 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003575 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3577 if (SHOW_INFO || Config.LOGV) {
3578 Log.v(TAG, " IntentFilter:");
3579 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3580 }
3581 removeFilter(intent);
3582 }
3583 }
3584
3585 @Override
3586 protected boolean allowFilterResult(
3587 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3588 ActivityInfo filterAi = filter.activity.info;
3589 for (int i=dest.size()-1; i>=0; i--) {
3590 ActivityInfo destAi = dest.get(i).activityInfo;
3591 if (destAi.name == filterAi.name
3592 && destAi.packageName == filterAi.packageName) {
3593 return false;
3594 }
3595 }
3596 return true;
3597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 @Override
3600 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3601 int match) {
3602 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3603 return null;
3604 }
3605 final PackageParser.Activity activity = info.activity;
3606 if (mSafeMode && (activity.info.applicationInfo.flags
3607 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3608 return null;
3609 }
3610 final ResolveInfo res = new ResolveInfo();
3611 res.activityInfo = PackageParser.generateActivityInfo(activity,
3612 mFlags);
3613 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3614 res.filter = info;
3615 }
3616 res.priority = info.getPriority();
3617 res.preferredOrder = activity.owner.mPreferredOrder;
3618 //System.out.println("Result: " + res.activityInfo.className +
3619 // " = " + res.priority);
3620 res.match = match;
3621 res.isDefault = info.hasDefault;
3622 res.labelRes = info.labelRes;
3623 res.nonLocalizedLabel = info.nonLocalizedLabel;
3624 res.icon = info.icon;
3625 return res;
3626 }
3627
3628 @Override
3629 protected void sortResults(List<ResolveInfo> results) {
3630 Collections.sort(results, mResolvePrioritySorter);
3631 }
3632
3633 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003634 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003636 out.print(prefix); out.print(
3637 Integer.toHexString(System.identityHashCode(filter.activity)));
3638 out.print(' ');
3639 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 }
3641
3642// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3643// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3644// final List<ResolveInfo> retList = Lists.newArrayList();
3645// while (i.hasNext()) {
3646// final ResolveInfo resolveInfo = i.next();
3647// if (isEnabledLP(resolveInfo.activityInfo)) {
3648// retList.add(resolveInfo);
3649// }
3650// }
3651// return retList;
3652// }
3653
3654 // Keys are String (activity class name), values are Activity.
3655 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3656 = new HashMap<ComponentName, PackageParser.Activity>();
3657 private int mFlags;
3658 }
3659
3660 private final class ServiceIntentResolver
3661 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003662 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003664 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 }
3666
Mihai Preda074edef2009-05-18 17:13:31 +02003667 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003669 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3671 }
3672
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003673 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3674 ArrayList<PackageParser.Service> packageServices) {
3675 if (packageServices == null) {
3676 return null;
3677 }
3678 mFlags = flags;
3679 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3680 int N = packageServices.size();
3681 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3682 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3683
3684 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3685 for (int i = 0; i < N; ++i) {
3686 intentFilters = packageServices.get(i).intents;
3687 if (intentFilters != null && intentFilters.size() > 0) {
3688 listCut.add(intentFilters);
3689 }
3690 }
3691 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3692 }
3693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 public final void addService(PackageParser.Service s) {
3695 mServices.put(s.component, s);
3696 if (SHOW_INFO || Config.LOGV) Log.v(
3697 TAG, " " + (s.info.nonLocalizedLabel != null
3698 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3699 if (SHOW_INFO || Config.LOGV) Log.v(
3700 TAG, " Class=" + s.info.name);
3701 int NI = s.intents.size();
3702 int j;
3703 for (j=0; j<NI; j++) {
3704 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3705 if (SHOW_INFO || Config.LOGV) {
3706 Log.v(TAG, " IntentFilter:");
3707 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3708 }
3709 if (!intent.debugCheck()) {
3710 Log.w(TAG, "==> For Service " + s.info.name);
3711 }
3712 addFilter(intent);
3713 }
3714 }
3715
3716 public final void removeService(PackageParser.Service s) {
3717 mServices.remove(s.component);
3718 if (SHOW_INFO || Config.LOGV) Log.v(
3719 TAG, " " + (s.info.nonLocalizedLabel != null
3720 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3721 if (SHOW_INFO || Config.LOGV) Log.v(
3722 TAG, " Class=" + s.info.name);
3723 int NI = s.intents.size();
3724 int j;
3725 for (j=0; j<NI; j++) {
3726 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3727 if (SHOW_INFO || Config.LOGV) {
3728 Log.v(TAG, " IntentFilter:");
3729 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3730 }
3731 removeFilter(intent);
3732 }
3733 }
3734
3735 @Override
3736 protected boolean allowFilterResult(
3737 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3738 ServiceInfo filterSi = filter.service.info;
3739 for (int i=dest.size()-1; i>=0; i--) {
3740 ServiceInfo destAi = dest.get(i).serviceInfo;
3741 if (destAi.name == filterSi.name
3742 && destAi.packageName == filterSi.packageName) {
3743 return false;
3744 }
3745 }
3746 return true;
3747 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 @Override
3750 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3751 int match) {
3752 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3753 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3754 return null;
3755 }
3756 final PackageParser.Service service = info.service;
3757 if (mSafeMode && (service.info.applicationInfo.flags
3758 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3759 return null;
3760 }
3761 final ResolveInfo res = new ResolveInfo();
3762 res.serviceInfo = PackageParser.generateServiceInfo(service,
3763 mFlags);
3764 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3765 res.filter = filter;
3766 }
3767 res.priority = info.getPriority();
3768 res.preferredOrder = service.owner.mPreferredOrder;
3769 //System.out.println("Result: " + res.activityInfo.className +
3770 // " = " + res.priority);
3771 res.match = match;
3772 res.isDefault = info.hasDefault;
3773 res.labelRes = info.labelRes;
3774 res.nonLocalizedLabel = info.nonLocalizedLabel;
3775 res.icon = info.icon;
3776 return res;
3777 }
3778
3779 @Override
3780 protected void sortResults(List<ResolveInfo> results) {
3781 Collections.sort(results, mResolvePrioritySorter);
3782 }
3783
3784 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003785 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003787 out.print(prefix); out.print(
3788 Integer.toHexString(System.identityHashCode(filter.service)));
3789 out.print(' ');
3790 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 }
3792
3793// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3794// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3795// final List<ResolveInfo> retList = Lists.newArrayList();
3796// while (i.hasNext()) {
3797// final ResolveInfo resolveInfo = (ResolveInfo) i;
3798// if (isEnabledLP(resolveInfo.serviceInfo)) {
3799// retList.add(resolveInfo);
3800// }
3801// }
3802// return retList;
3803// }
3804
3805 // Keys are String (activity class name), values are Activity.
3806 private final HashMap<ComponentName, PackageParser.Service> mServices
3807 = new HashMap<ComponentName, PackageParser.Service>();
3808 private int mFlags;
3809 };
3810
3811 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3812 new Comparator<ResolveInfo>() {
3813 public int compare(ResolveInfo r1, ResolveInfo r2) {
3814 int v1 = r1.priority;
3815 int v2 = r2.priority;
3816 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3817 if (v1 != v2) {
3818 return (v1 > v2) ? -1 : 1;
3819 }
3820 v1 = r1.preferredOrder;
3821 v2 = r2.preferredOrder;
3822 if (v1 != v2) {
3823 return (v1 > v2) ? -1 : 1;
3824 }
3825 if (r1.isDefault != r2.isDefault) {
3826 return r1.isDefault ? -1 : 1;
3827 }
3828 v1 = r1.match;
3829 v2 = r2.match;
3830 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3831 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3832 }
3833 };
3834
3835 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3836 new Comparator<ProviderInfo>() {
3837 public int compare(ProviderInfo p1, ProviderInfo p2) {
3838 final int v1 = p1.initOrder;
3839 final int v2 = p2.initOrder;
3840 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3841 }
3842 };
3843
3844 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3845 IActivityManager am = ActivityManagerNative.getDefault();
3846 if (am != null) {
3847 try {
3848 final Intent intent = new Intent(action,
3849 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3850 if (extras != null) {
3851 intent.putExtras(extras);
3852 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003853 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 am.broadcastIntent(
3855 null, intent,
3856 null, null, 0, null, null, null, false, false);
3857 } catch (RemoteException ex) {
3858 }
3859 }
3860 }
3861
3862 private final class AppDirObserver extends FileObserver {
3863 public AppDirObserver(String path, int mask, boolean isrom) {
3864 super(path, mask);
3865 mRootDir = path;
3866 mIsRom = isrom;
3867 }
3868
3869 public void onEvent(int event, String path) {
3870 String removedPackage = null;
3871 int removedUid = -1;
3872 String addedPackage = null;
3873 int addedUid = -1;
3874
3875 synchronized (mInstallLock) {
3876 String fullPathStr = null;
3877 File fullPath = null;
3878 if (path != null) {
3879 fullPath = new File(mRootDir, path);
3880 fullPathStr = fullPath.getPath();
3881 }
3882
3883 if (Config.LOGV) Log.v(
3884 TAG, "File " + fullPathStr + " changed: "
3885 + Integer.toHexString(event));
3886
3887 if (!isPackageFilename(path)) {
3888 if (Config.LOGV) Log.v(
3889 TAG, "Ignoring change of non-package file: " + fullPathStr);
3890 return;
3891 }
3892
3893 if ((event&REMOVE_EVENTS) != 0) {
3894 synchronized (mInstallLock) {
3895 PackageParser.Package p = mAppDirs.get(fullPathStr);
3896 if (p != null) {
3897 removePackageLI(p, true);
3898 removedPackage = p.applicationInfo.packageName;
3899 removedUid = p.applicationInfo.uid;
3900 }
3901 }
3902 }
3903
3904 if ((event&ADD_EVENTS) != 0) {
3905 PackageParser.Package p = mAppDirs.get(fullPathStr);
3906 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003907 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3909 PackageParser.PARSE_CHATTY |
3910 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08003911 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if (p != null) {
3913 synchronized (mPackages) {
3914 grantPermissionsLP(p, false);
3915 }
3916 addedPackage = p.applicationInfo.packageName;
3917 addedUid = p.applicationInfo.uid;
3918 }
3919 }
3920 }
3921
3922 synchronized (mPackages) {
3923 mSettings.writeLP();
3924 }
3925 }
3926
3927 if (removedPackage != null) {
3928 Bundle extras = new Bundle(1);
3929 extras.putInt(Intent.EXTRA_UID, removedUid);
3930 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3931 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3932 }
3933 if (addedPackage != null) {
3934 Bundle extras = new Bundle(1);
3935 extras.putInt(Intent.EXTRA_UID, addedUid);
3936 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3937 }
3938 }
3939
3940 private final String mRootDir;
3941 private final boolean mIsRom;
3942 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 /* Called when a downloaded package installation has been confirmed by the user */
3945 public void installPackage(
3946 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003947 installPackage(packageURI, observer, flags, null);
3948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003949
Jacek Surazski65e13172009-04-28 15:26:38 +02003950 /* Called when a downloaded package installation has been confirmed by the user */
3951 public void installPackage(
3952 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3953 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 mContext.enforceCallingOrSelfPermission(
3955 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003956
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003957 Message msg = mHandler.obtainMessage(INIT_COPY);
3958 msg.obj = createInstallArgs(packageURI, observer, flags, installerPackageName);
3959 mHandler.sendMessage(msg);
3960 }
3961
3962 private InstallArgs createInstallArgs(Uri packageURI, IPackageInstallObserver observer,
3963 int flags, String installerPackageName) {
3964 if (installOnSd(flags)) {
3965 return new SdInstallArgs(packageURI, observer, flags,
3966 installerPackageName);
3967 } else {
3968 return new FileInstallArgs(packageURI, observer, flags,
3969 installerPackageName);
3970 }
3971 }
3972
3973 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
3974 if (installOnSd(flags)) {
3975 return new SdInstallArgs(fullCodePath, fullResourcePath);
3976 } else {
3977 return new FileInstallArgs(fullCodePath, fullResourcePath);
3978 }
3979 }
3980
3981 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 // Queue up an async operation since the package installation may take a little while.
3983 mHandler.post(new Runnable() {
3984 public void run() {
3985 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003986 // Result object to be returned
3987 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003988 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003989 res.uid = -1;
3990 res.pkg = null;
3991 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003992 args.doPreInstall(res.returnCode);
3993 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003994 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003995 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003996 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003997 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003999 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004001 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 } catch (RemoteException e) {
4003 Log.i(TAG, "Observer no longer exists.");
4004 }
4005 }
4006 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4007 // call appears in the synchronized block above.
4008 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4009 res.removedInfo.sendBroadcast(false, true);
4010 Bundle extras = new Bundle(1);
4011 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004012 final boolean update = res.removedInfo.removedPackage != null;
4013 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4015 }
4016 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4017 res.pkg.applicationInfo.packageName,
4018 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004019 if (update) {
4020 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4021 res.pkg.applicationInfo.packageName,
4022 extras);
4023 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004024 if (res.removedInfo.args != null) {
4025 // Remove the replaced package's older resources safely now
4026 synchronized (mInstallLock) {
4027 res.removedInfo.args.cleanUpResourcesLI();
4028 }
4029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031 Runtime.getRuntime().gc();
4032 }
4033 });
4034 }
4035
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004036 static abstract class InstallArgs {
4037 final IPackageInstallObserver observer;
4038 final int flags;
4039 final Uri packageURI;
4040 final String installerPackageName;
4041
4042 InstallArgs(Uri packageURI,
4043 IPackageInstallObserver observer, int flags,
4044 String installerPackageName) {
4045 this.packageURI = packageURI;
4046 this.flags = flags;
4047 this.observer = observer;
4048 this.installerPackageName = installerPackageName;
4049 }
4050
4051 abstract void createCopyFile();
4052 abstract int copyApk(IMediaContainerService imcs);
4053 abstract void doPreInstall(int status);
4054 abstract boolean doRename(int status, String pkgName, String oldCodePath);
4055 abstract void doPostInstall(int status);
4056 abstract String getCodePath();
4057 abstract String getResourcePath();
4058 // Need installer lock especially for dex file removal.
4059 abstract void cleanUpResourcesLI();
4060 }
4061
4062 class FileInstallArgs extends InstallArgs {
4063 File installDir;
4064 String codeFileName;
4065 String resourceFileName;
4066
4067 FileInstallArgs(Uri packageURI,
4068 IPackageInstallObserver observer, int flags,
4069 String installerPackageName) {
4070 super(packageURI, observer, flags, installerPackageName);
4071 }
4072
4073 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4074 super(null, null, 0, null);
4075 File codeFile = new File(fullCodePath);
4076 installDir = codeFile.getParentFile();
4077 codeFileName = fullCodePath;
4078 resourceFileName = fullResourcePath;
4079 }
4080
4081 void createCopyFile() {
4082 boolean fwdLocked = isFwdLocked(flags);
4083 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4084 codeFileName = createTempPackageFile(installDir).getPath();
4085 resourceFileName = getResourcePathFromCodePath();
4086 }
4087
4088 String getCodePath() {
4089 return codeFileName;
4090 }
4091
4092 int copyApk(IMediaContainerService imcs) {
4093 // Get a ParcelFileDescriptor to write to the output file
4094 File codeFile = new File(codeFileName);
4095 ParcelFileDescriptor out = null;
4096 try {
4097 out = ParcelFileDescriptor.open(codeFile,
4098 ParcelFileDescriptor.MODE_READ_WRITE);
4099 } catch (FileNotFoundException e) {
4100 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4101 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4102 }
4103 // Copy the resource now
4104 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4105 try {
4106 if (imcs.copyResource(packageURI, out)) {
4107 ret = PackageManager.INSTALL_SUCCEEDED;
4108 }
4109 } catch (RemoteException e) {
4110 } finally {
4111 try { if (out != null) out.close(); } catch (IOException e) {}
4112 }
4113 return ret;
4114 }
4115
4116 void doPreInstall(int status) {
4117 if (status != PackageManager.INSTALL_SUCCEEDED) {
4118 cleanUp();
4119 }
4120 }
4121
4122 boolean doRename(int status, final String pkgName, String oldCodePath) {
4123 if (status != PackageManager.INSTALL_SUCCEEDED) {
4124 cleanUp();
4125 return false;
4126 } else {
4127 // Rename based on packageName
4128 File codeFile = new File(getCodePath());
4129 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4130 File desFile = new File(installDir, apkName + ".apk");
4131 if (!codeFile.renameTo(desFile)) {
4132 return false;
4133 }
4134 // Reset paths since the file has been renamed.
4135 codeFileName = desFile.getPath();
4136 resourceFileName = getResourcePathFromCodePath();
4137 // Set permissions
4138 if (!setPermissions(pkgName)) {
4139 // Failed setting permissions.
4140 return false;
4141 }
4142 return true;
4143 }
4144 }
4145
4146 void doPostInstall(int status) {
4147 if (status != PackageManager.INSTALL_SUCCEEDED) {
4148 cleanUp();
4149 }
4150 }
4151
4152 String getResourcePath() {
4153 return resourceFileName;
4154 }
4155
4156 String getResourcePathFromCodePath() {
4157 String codePath = getCodePath();
4158 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4159 String apkNameOnly = getApkName(codePath);
4160 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4161 } else {
4162 return codePath;
4163 }
4164 }
4165
4166 private boolean cleanUp() {
4167 boolean ret = true;
4168 String sourceDir = getCodePath();
4169 String publicSourceDir = getResourcePath();
4170 if (sourceDir != null) {
4171 File sourceFile = new File(sourceDir);
4172 if (!sourceFile.exists()) {
4173 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4174 ret = false;
4175 }
4176 // Delete application's code and resources
4177 sourceFile.delete();
4178 }
4179 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4180 final File publicSourceFile = new File(publicSourceDir);
4181 if (!publicSourceFile.exists()) {
4182 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4183 }
4184 if (publicSourceFile.exists()) {
4185 publicSourceFile.delete();
4186 }
4187 }
4188 return ret;
4189 }
4190
4191 void cleanUpResourcesLI() {
4192 String sourceDir = getCodePath();
4193 if (cleanUp() && mInstaller != null) {
4194 int retCode = mInstaller.rmdex(sourceDir);
4195 if (retCode < 0) {
4196 Log.w(TAG, "Couldn't remove dex file for package: "
4197 + " at location "
4198 + sourceDir + ", retcode=" + retCode);
4199 // we don't consider this to be a failure of the core package deletion
4200 }
4201 }
4202 }
4203
4204 private boolean setPermissions(String pkgName) {
4205 // TODO Do this in a more elegant way later on. for now just a hack
4206 if (!isFwdLocked(flags)) {
4207 final int filePermissions =
4208 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4209 |FileUtils.S_IROTH;
4210 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4211 if (retCode != 0) {
4212 Log.e(TAG, "Couldn't set new package file permissions for " +
4213 getCodePath()
4214 + ". The return code was: " + retCode);
4215 // TODO Define new internal error
4216 return false;
4217 }
4218 return true;
4219 }
4220 return true;
4221 }
4222 }
4223
4224 class SdInstallArgs extends InstallArgs {
4225 String cid;
4226 String cachePath;
4227 static final String RES_FILE_NAME = "pkg.apk";
4228
4229 SdInstallArgs(Uri packageURI,
4230 IPackageInstallObserver observer, int flags,
4231 String installerPackageName) {
4232 super(packageURI, observer, flags, installerPackageName);
4233 }
4234
4235 SdInstallArgs(String fullCodePath, String fullResourcePath) {
4236 super(null, null, 0, null);
4237 // Extract cid from fullCodePath
4238 int eidx = fullCodePath.lastIndexOf("/");
4239 String subStr1 = fullCodePath.substring(0, eidx);
4240 int sidx = subStr1.lastIndexOf("/");
4241 cid = subStr1.substring(sidx+1, eidx);
4242 cachePath = subStr1;
4243 }
4244
4245 void createCopyFile() {
4246 cid = getTempContainerId();
4247 }
4248
4249 int copyApk(IMediaContainerService imcs) {
4250 try {
4251 cachePath = imcs.copyResourceToContainer(
4252 packageURI, cid,
4253 getEncryptKey(), RES_FILE_NAME);
4254 } catch (RemoteException e) {
4255 }
4256
4257 if (cachePath != null) {
4258 // Mount container once its created with system_uid
4259 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4260 }
4261 if (cachePath == null) {
4262 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4263 } else {
4264 return PackageManager.INSTALL_SUCCEEDED;
4265 }
4266 }
4267
4268 @Override
4269 String getCodePath() {
4270 return cachePath + "/" + RES_FILE_NAME;
4271 }
4272
4273 @Override
4274 String getResourcePath() {
4275 return cachePath + "/" + RES_FILE_NAME;
4276 }
4277
4278 void doPreInstall(int status) {
4279 if (status != PackageManager.INSTALL_SUCCEEDED) {
4280 // Destroy container
4281 destroySdDir(cid);
4282 }
4283 }
4284
4285 boolean doRename(int status, final String pkgName,
4286 String oldCodePath) {
4287 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
4288 // STOPSHIP TEMPORARY HACK FOR RENAME
4289 // Create new container at newCachePath
4290 String codePath = getCodePath();
4291 String newCachePath = null;
4292 final int CREATE_FAILED = 1;
4293 final int COPY_FAILED = 3;
4294 final int FINALIZE_FAILED = 5;
4295 final int PASS = 7;
4296 int errCode = CREATE_FAILED;
4297 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4298 errCode = COPY_FAILED;
4299 // Copy file from codePath
4300 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4301 errCode = FINALIZE_FAILED;
4302 if (finalizeSdDir(newCacheId)) {
4303 errCode = PASS;
4304 }
4305 }
4306 }
4307 // Print error based on errCode
4308 String errMsg = "";
4309 switch (errCode) {
4310 case CREATE_FAILED:
4311 errMsg = "CREATE_FAILED";
4312 break;
4313 case COPY_FAILED:
4314 errMsg = "COPY_FAILED";
4315 destroySdDir(newCacheId);
4316 break;
4317 case FINALIZE_FAILED:
4318 errMsg = "FINALIZE_FAILED";
4319 destroySdDir(newCacheId);
4320 break;
4321 default:
4322 errMsg = "PASS";
4323 break;
4324 }
4325 // Destroy the temporary container
4326 destroySdDir(cid);
4327 Log.i(TAG, "Status: " + errMsg);
4328 if (errCode != PASS) {
4329 return false;
4330 }
4331 cid = newCacheId;
4332 cachePath = newCachePath;
4333
4334 return true;
4335 }
4336
4337 void doPostInstall(int status) {
4338 if (status != PackageManager.INSTALL_SUCCEEDED) {
4339 cleanUp();
4340 } else {
4341 // Unmount container
4342 // Rename and remount based on package name and new uid
4343 }
4344 }
4345
4346 private void cleanUp() {
4347 // Destroy secure container
4348 destroySdDir(cid);
4349 }
4350
4351 void cleanUpResourcesLI() {
4352 String sourceFile = getCodePath();
4353 // Remove dex file
4354 if (mInstaller != null) {
4355 int retCode = mInstaller.rmdex(sourceFile.toString());
4356 if (retCode < 0) {
4357 Log.w(TAG, "Couldn't remove dex file for package: "
4358 + " at location "
4359 + sourceFile.toString() + ", retcode=" + retCode);
4360 // we don't consider this to be a failure of the core package deletion
4361 }
4362 }
4363 cleanUp();
4364 }
4365 };
4366
4367 // Utility method used to create code paths based on package name and available index.
4368 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4369 String idxStr = "";
4370 int idx = 1;
4371 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004372 String subStr = oldCodePath;
4373 if (subStr.startsWith(prefix)) {
4374 subStr = subStr.substring(prefix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004375 }
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004376 if (subStr.endsWith(suffix)) {
4377 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004378 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004379 if (subStr != null) {
4380 if (subStr.startsWith("-")) {
4381 subStr = subStr.substring(1);
4382 }
4383 try {
4384 idx = Integer.parseInt(subStr);
4385 if (idx <= 1) {
4386 idx++;
4387 } else {
4388 idx--;
4389 }
4390 } catch(NumberFormatException e) {
4391 }
4392 }
4393 }
4394 idxStr = "-" + Integer.toString(idx);
4395 return prefix + idxStr;
4396 }
4397
4398 // Utility method that returns the relative package path with respect
4399 // to the installation directory. Like say for /data/data/com.test-1.apk
4400 // string com.test-1 is returned.
4401 static String getApkName(String codePath) {
4402 if (codePath == null) {
4403 return null;
4404 }
4405 int sidx = codePath.lastIndexOf("/");
4406 int eidx = codePath.lastIndexOf(".");
4407 if (eidx == -1) {
4408 eidx = codePath.length();
4409 } else if (eidx == 0) {
4410 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4411 return null;
4412 }
4413 return codePath.substring(sidx+1, eidx);
4414 }
4415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 class PackageInstalledInfo {
4417 String name;
4418 int uid;
4419 PackageParser.Package pkg;
4420 int returnCode;
4421 PackageRemovedInfo removedInfo;
4422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 /*
4425 * Install a non-existing package.
4426 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004427 private void installNewPackageLI(PackageParser.Package pkg,
4428 int parseFlags,
4429 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004430 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004432 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004433 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004434
4435 if (useEncryptedFilesystemForPackage(pkg)) {
4436 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4437 } else {
4438 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 res.name = pkgName;
4441 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004442 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004444 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 + " without first uninstalling.");
4446 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4447 return;
4448 }
4449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004451 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004453 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4455 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4456 }
4457 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004458 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004459 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 res);
4461 // delete the partially installed application. the data directory will have to be
4462 // restored if it was already existing
4463 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4464 // remove package from internal structures. Note that we want deletePackageX to
4465 // delete the package data and cache directories that it created in
4466 // scanPackageLocked, unless those directories existed before we even tried to
4467 // install.
4468 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004469 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4471 res.removedInfo);
4472 }
4473 }
4474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004475
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004476 private void replacePackageLI(PackageParser.Package pkg,
4477 int parseFlags,
4478 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004479 String installerPackageName, PackageInstalledInfo res) {
4480
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004481 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004482 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 // First find the old package info and check signatures
4484 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004485 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004486 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
4487 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4489 return;
4490 }
4491 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004492 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 if(sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004494 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004496 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004501 PackageParser.Package pkg,
4502 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004503 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 PackageParser.Package newPackage = null;
4505 String pkgName = deletedPackage.packageName;
4506 boolean deletedPkg = true;
4507 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004508
Jacek Surazski65e13172009-04-28 15:26:38 +02004509 String oldInstallerPackageName = null;
4510 synchronized (mPackages) {
4511 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004513
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004514 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004516 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 res.removedInfo)) {
4518 // If the existing package was'nt successfully deleted
4519 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4520 deletedPkg = false;
4521 } else {
4522 // Successfully deleted the old package. Now proceed with re-installation
4523 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004524 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004526 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4528 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004529 }
4530 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004531 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004532 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 res);
4534 updatedSettings = true;
4535 }
4536 }
4537
4538 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4539 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004540 // were keeping around in case we needed them (see below) can now be deleted.
4541 // This info will be set on the res.removedInfo to clean up later on as post
4542 // install action.
4543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 //update signature on the new package setting
4545 //this should always succeed, since we checked the
4546 //signature earlier.
4547 synchronized(mPackages) {
4548 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4549 parseFlags, true);
4550 }
4551 } else {
4552 // remove package from internal structures. Note that we want deletePackageX to
4553 // delete the package data and cache directories that it created in
4554 // scanPackageLocked, unless those directories existed before we even tried to
4555 // install.
4556 if(updatedSettings) {
4557 deletePackageLI(
4558 pkgName, true,
4559 PackageManager.DONT_DELETE_DATA,
4560 res.removedInfo);
4561 }
4562 // Since we failed to install the new package we need to restore the old
4563 // package that we deleted.
4564 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004565 File restoreFile = new File(deletedPackage.mPath);
4566 if (restoreFile == null) {
4567 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4568 return;
4569 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004570 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4571 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004572 // Parse old package
4573 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
4574 scanPackageLI(restoreFile, parseFlags, scanMode);
4575 synchronized (mPackages) {
4576 grantPermissionsLP(deletedPackage, false);
4577 mSettings.writeLP();
4578 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004579 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4580 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 }
4583 }
4584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004587 PackageParser.Package pkg,
4588 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004589 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 PackageParser.Package newPackage = null;
4591 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004592 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 PackageParser.PARSE_IS_SYSTEM;
4594 String packageName = deletedPackage.packageName;
4595 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4596 if (packageName == null) {
4597 Log.w(TAG, "Attempt to delete null packageName.");
4598 return;
4599 }
4600 PackageParser.Package oldPkg;
4601 PackageSetting oldPkgSetting;
4602 synchronized (mPackages) {
4603 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004604 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4606 (oldPkgSetting == null)) {
4607 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4608 return;
4609 }
4610 }
4611 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4612 res.removedInfo.removedPackage = packageName;
4613 // Remove existing system package
4614 removePackageLI(oldPkg, true);
4615 synchronized (mPackages) {
4616 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4617 }
4618
4619 // Successfully disabled the old package. Now proceed with re-installation
4620 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4621 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004622 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004624 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4626 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4627 }
4628 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004629 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 updatedSettings = true;
4631 }
4632
4633 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4634 //update signature on the new package setting
4635 //this should always succeed, since we checked the
4636 //signature earlier.
4637 synchronized(mPackages) {
4638 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4639 parseFlags, true);
4640 }
4641 } else {
4642 // Re installation failed. Restore old information
4643 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004644 if (newPackage != null) {
4645 removePackageLI(newPackage, true);
4646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004648 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004650 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 // Restore the old system information in Settings
4652 synchronized(mPackages) {
4653 if(updatedSettings) {
4654 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004655 mSettings.setInstallerPackageName(packageName,
4656 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 }
4658 mSettings.writeLP();
4659 }
4660 }
4661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004662
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004663 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004664 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004665 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004666 synchronized (mPackages) {
4667 //write settings. the installStatus will be incomplete at this stage.
4668 //note that the new package setting would have already been
4669 //added to mPackages. It hasn't been persisted yet.
4670 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4671 mSettings.writeLP();
4672 }
4673
4674 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004675 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4676 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004678 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004679 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4680 return;
4681 }
4682 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004683 res.returnCode = setPermissionsLI(newPackage);
4684 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4685 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004687 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004688 }
4689 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4690 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004691 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004692 }
4693 }
4694
4695 synchronized (mPackages) {
4696 grantPermissionsLP(newPackage, true);
4697 res.name = pkgName;
4698 res.uid = newPackage.applicationInfo.uid;
4699 res.pkg = newPackage;
4700 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004701 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4703 //to update install status
4704 mSettings.writeLP();
4705 }
4706 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004707
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004708 private void installPackageLI(InstallArgs args,
4709 boolean newInstall, PackageInstalledInfo res) {
4710 int pFlags = args.flags;
4711 String installerPackageName = args.installerPackageName;
4712 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004713 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
4714 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004715 boolean replacingExistingPackage = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004716 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
4717 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004718 // Result object to be returned
4719 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4720
4721 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 // Retrieve PackageSettings and parse package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004723 int parseFlags = PackageParser.PARSE_CHATTY |
4724 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
4725 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 parseFlags |= mDefParseFlags;
4727 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4728 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004730 null, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 if (pkg == null) {
4732 res.returnCode = pp.getParseError();
4733 break main_flow;
4734 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004735 String pkgName = res.name = pkg.packageName;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004736 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4737 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4738 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4739 break main_flow;
4740 }
4741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4743 res.returnCode = pp.getParseError();
4744 break main_flow;
4745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004746
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004747 // Get rid of all references to package scan path via parser.
4748 pp = null;
4749 String oldCodePath = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 synchronized (mPackages) {
4751 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004752 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 && mPackages.containsKey(pkgName)) {
4754 replacingExistingPackage = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004755 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756 }
4757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004758
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004759 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
4760 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4761 break main_flow;
4762 }
4763 // TODO rename pkg.mScanPath In scanPackageLI let it just set values based on mScanPath
4764 pkg.applicationInfo.sourceDir = pkg.mScanPath= pkg.mPath = args.getCodePath();
4765 pkg.applicationInfo.publicSourceDir = args.getResourcePath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 if(replacingExistingPackage) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004767 replacePackageLI(pkg, parseFlags, scanMode,
4768 installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004770 installNewPackageLI(pkg, parseFlags, scanMode,
4771 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004772 }
4773 } finally {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004774 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004778
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004779 private int setPermissionsLI(PackageParser.Package newPackage) {
4780 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004781 int retCode = 0;
4782 // TODO Gross hack but fix later. Ideally move this to be a post installation
4783 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004784 if ((newPackage.applicationInfo.flags
4785 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
4786 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 try {
4788 extractPublicFiles(newPackage, destResourceFile);
4789 } catch (IOException e) {
4790 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4791 " forward-locked app.");
4792 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4793 } finally {
4794 //TODO clean up the extracted public files
4795 }
4796 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004797 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 newPackage.applicationInfo.uid);
4799 } else {
4800 final int filePermissions =
4801 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004802 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 newPackage.applicationInfo.uid);
4804 }
4805 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004806 // The permissions on the resource file was set when it was copied for
4807 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004811 Log.e(TAG, "Couldn't set new package file permissions for " +
4812 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004813 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004814 // TODO Define new internal error
4815 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 }
4817 return PackageManager.INSTALL_SUCCEEDED;
4818 }
4819
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004820 private boolean isForwardLocked(PackageParser.Package pkg) {
4821 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 }
4823
4824 private void extractPublicFiles(PackageParser.Package newPackage,
4825 File publicZipFile) throws IOException {
4826 final ZipOutputStream publicZipOutStream =
4827 new ZipOutputStream(new FileOutputStream(publicZipFile));
4828 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4829
4830 // Copy manifest, resources.arsc and res directory to public zip
4831
4832 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4833 while (privateZipEntries.hasMoreElements()) {
4834 final ZipEntry zipEntry = privateZipEntries.nextElement();
4835 final String zipEntryName = zipEntry.getName();
4836 if ("AndroidManifest.xml".equals(zipEntryName)
4837 || "resources.arsc".equals(zipEntryName)
4838 || zipEntryName.startsWith("res/")) {
4839 try {
4840 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4841 } catch (IOException e) {
4842 try {
4843 publicZipOutStream.close();
4844 throw e;
4845 } finally {
4846 publicZipFile.delete();
4847 }
4848 }
4849 }
4850 }
4851
4852 publicZipOutStream.close();
4853 FileUtils.setPermissions(
4854 publicZipFile.getAbsolutePath(),
4855 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4856 -1, -1);
4857 }
4858
4859 private static void copyZipEntry(ZipEntry zipEntry,
4860 ZipFile inZipFile,
4861 ZipOutputStream outZipStream) throws IOException {
4862 byte[] buffer = new byte[4096];
4863 int num;
4864
4865 ZipEntry newEntry;
4866 if (zipEntry.getMethod() == ZipEntry.STORED) {
4867 // Preserve the STORED method of the input entry.
4868 newEntry = new ZipEntry(zipEntry);
4869 } else {
4870 // Create a new entry so that the compressed len is recomputed.
4871 newEntry = new ZipEntry(zipEntry.getName());
4872 }
4873 outZipStream.putNextEntry(newEntry);
4874
4875 InputStream data = inZipFile.getInputStream(zipEntry);
4876 while ((num = data.read(buffer)) > 0) {
4877 outZipStream.write(buffer, 0, num);
4878 }
4879 outZipStream.flush();
4880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 private void deleteTempPackageFiles() {
4883 FilenameFilter filter = new FilenameFilter() {
4884 public boolean accept(File dir, String name) {
4885 return name.startsWith("vmdl") && name.endsWith(".tmp");
4886 }
4887 };
4888 String tmpFilesList[] = mAppInstallDir.list(filter);
4889 if(tmpFilesList == null) {
4890 return;
4891 }
4892 for(int i = 0; i < tmpFilesList.length; i++) {
4893 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4894 tmpFile.delete();
4895 }
4896 }
4897
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004898 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 File tmpPackageFile;
4900 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004901 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 } catch (IOException e) {
4903 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4904 return null;
4905 }
4906 try {
4907 FileUtils.setPermissions(
4908 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4909 -1, -1);
4910 } catch (IOException e) {
4911 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4912 return null;
4913 }
4914 return tmpPackageFile;
4915 }
4916
4917 public void deletePackage(final String packageName,
4918 final IPackageDeleteObserver observer,
4919 final int flags) {
4920 mContext.enforceCallingOrSelfPermission(
4921 android.Manifest.permission.DELETE_PACKAGES, null);
4922 // Queue up an async operation since the package deletion may take a little while.
4923 mHandler.post(new Runnable() {
4924 public void run() {
4925 mHandler.removeCallbacks(this);
4926 final boolean succeded = deletePackageX(packageName, true, true, flags);
4927 if (observer != null) {
4928 try {
4929 observer.packageDeleted(succeded);
4930 } catch (RemoteException e) {
4931 Log.i(TAG, "Observer no longer exists.");
4932 } //end catch
4933 } //end if
4934 } //end run
4935 });
4936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 /**
4939 * This method is an internal method that could be get invoked either
4940 * to delete an installed package or to clean up a failed installation.
4941 * After deleting an installed package, a broadcast is sent to notify any
4942 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004943 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 * installation wouldn't have sent the initial broadcast either
4945 * The key steps in deleting a package are
4946 * deleting the package information in internal structures like mPackages,
4947 * deleting the packages base directories through installd
4948 * updating mSettings to reflect current status
4949 * persisting settings for later use
4950 * sending a broadcast if necessary
4951 */
4952
4953 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4954 boolean deleteCodeAndResources, int flags) {
4955 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004956 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957
4958 synchronized (mInstallLock) {
4959 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4960 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004963 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4964 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4965
4966 // If the removed package was a system update, the old system packaged
4967 // was re-enabled; we need to broadcast this information
4968 if (systemUpdate) {
4969 Bundle extras = new Bundle(1);
4970 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4971 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4972
4973 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4974 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 // Delete the resources here after sending the broadcast to let
4978 // other processes clean up before deleting resources.
4979 synchronized (mInstallLock) {
4980 if (info.args != null) {
4981 info.args.cleanUpResourcesLI();
4982 }
4983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 return res;
4985 }
4986
4987 static class PackageRemovedInfo {
4988 String removedPackage;
4989 int uid = -1;
4990 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004991 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 // Clean up resources deleted packages.
4993 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07004994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 void sendBroadcast(boolean fullRemove, boolean replacing) {
4996 Bundle extras = new Bundle(1);
4997 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4998 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4999 if (replacing) {
5000 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5001 }
5002 if (removedPackage != null) {
5003 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5004 }
5005 if (removedUid >= 0) {
5006 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5007 }
5008 }
5009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 /*
5012 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5013 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005014 * 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 -08005015 * delete a partially installed application.
5016 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005017 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 int flags) {
5019 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005020 if (outInfo != null) {
5021 outInfo.removedPackage = packageName;
5022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 removePackageLI(p, true);
5024 // Retrieve object to delete permissions for shared user later on
5025 PackageSetting deletedPs;
5026 synchronized (mPackages) {
5027 deletedPs = mSettings.mPackages.get(packageName);
5028 }
5029 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005030 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005032 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033 if (retCode < 0) {
5034 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5035 + packageName + ", retcode=" + retCode);
5036 // we don't consider this to be a failure of the core package deletion
5037 }
5038 } else {
5039 //for emulator
5040 PackageParser.Package pkg = mPackages.get(packageName);
5041 File dataDir = new File(pkg.applicationInfo.dataDir);
5042 dataDir.delete();
5043 }
5044 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005045 if (outInfo != null) {
5046 outInfo.removedUid = mSettings.removePackageLP(packageName);
5047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048 }
5049 }
5050 synchronized (mPackages) {
5051 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5052 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005053 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 }
5055 // Save settings now
5056 mSettings.writeLP ();
5057 }
5058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 /*
5061 * Tries to delete system package.
5062 */
5063 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005064 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 ApplicationInfo applicationInfo = p.applicationInfo;
5066 //applicable for non-partially installed applications only
5067 if (applicationInfo == null) {
5068 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5069 return false;
5070 }
5071 PackageSetting ps = null;
5072 // Confirm if the system package has been updated
5073 // An updated system app can be deleted. This will also have to restore
5074 // the system pkg from system partition
5075 synchronized (mPackages) {
5076 ps = mSettings.getDisabledSystemPkg(p.packageName);
5077 }
5078 if (ps == null) {
5079 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5080 return false;
5081 } else {
5082 Log.i(TAG, "Deleting system pkg from data partition");
5083 }
5084 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005085 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005086 boolean deleteCodeAndResources = false;
5087 if (ps.versionCode < p.mVersionCode) {
5088 // Delete code and resources for downgrades
5089 deleteCodeAndResources = true;
5090 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5091 flags &= ~PackageManager.DONT_DELETE_DATA;
5092 }
5093 } else {
5094 // Preserve data by setting flag
5095 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5096 flags |= PackageManager.DONT_DELETE_DATA;
5097 }
5098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5100 if (!ret) {
5101 return false;
5102 }
5103 synchronized (mPackages) {
5104 // Reinstate the old system package
5105 mSettings.enableSystemPackageLP(p.packageName);
5106 }
5107 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005108 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005110 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 if (newPkg == null) {
5113 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5114 return false;
5115 }
5116 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005117 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 mSettings.writeLP();
5119 }
5120 return true;
5121 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5124 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5125 ApplicationInfo applicationInfo = p.applicationInfo;
5126 if (applicationInfo == null) {
5127 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5128 return false;
5129 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005130 if (outInfo != null) {
5131 outInfo.uid = applicationInfo.uid;
5132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133
5134 // Delete package data from internal structures and also remove data if flag is set
5135 removePackageDataLI(p, outInfo, flags);
5136
5137 // Delete application code and resources
5138 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139 // TODO can pick up from PackageSettings as well
5140 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5141 PackageManager.INSTALL_ON_SDCARD : 0;
5142 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5143 PackageManager.INSTALL_FORWARD_LOCK : 0;
5144 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005145 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 }
5147 return true;
5148 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 /*
5151 * This method handles package deletion in general
5152 */
5153 private boolean deletePackageLI(String packageName,
5154 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5155 if (packageName == null) {
5156 Log.w(TAG, "Attempt to delete null packageName.");
5157 return false;
5158 }
5159 PackageParser.Package p;
5160 boolean dataOnly = false;
5161 synchronized (mPackages) {
5162 p = mPackages.get(packageName);
5163 if (p == null) {
5164 //this retrieves partially installed apps
5165 dataOnly = true;
5166 PackageSetting ps = mSettings.mPackages.get(packageName);
5167 if (ps == null) {
5168 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5169 return false;
5170 }
5171 p = ps.pkg;
5172 }
5173 }
5174 if (p == null) {
5175 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5176 return false;
5177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 if (dataOnly) {
5180 // Delete application data first
5181 removePackageDataLI(p, outInfo, flags);
5182 return true;
5183 }
5184 // At this point the package should have ApplicationInfo associated with it
5185 if (p.applicationInfo == null) {
5186 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5187 return false;
5188 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005189 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005190 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5191 Log.i(TAG, "Removing system package:"+p.packageName);
5192 // When an updated system application is deleted we delete the existing resources as well and
5193 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005194 ret = deleteSystemPackageLI(p, flags, outInfo);
5195 } else {
5196 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005197 // Kill application pre-emptively especially for apps on sd.
5198 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005199 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005201 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005204 public void clearApplicationUserData(final String packageName,
5205 final IPackageDataObserver observer) {
5206 mContext.enforceCallingOrSelfPermission(
5207 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5208 // Queue up an async operation since the package deletion may take a little while.
5209 mHandler.post(new Runnable() {
5210 public void run() {
5211 mHandler.removeCallbacks(this);
5212 final boolean succeeded;
5213 synchronized (mInstallLock) {
5214 succeeded = clearApplicationUserDataLI(packageName);
5215 }
5216 if (succeeded) {
5217 // invoke DeviceStorageMonitor's update method to clear any notifications
5218 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5219 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5220 if (dsm != null) {
5221 dsm.updateMemory();
5222 }
5223 }
5224 if(observer != null) {
5225 try {
5226 observer.onRemoveCompleted(packageName, succeeded);
5227 } catch (RemoteException e) {
5228 Log.i(TAG, "Observer no longer exists.");
5229 }
5230 } //end if observer
5231 } //end run
5232 });
5233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 private boolean clearApplicationUserDataLI(String packageName) {
5236 if (packageName == null) {
5237 Log.w(TAG, "Attempt to delete null packageName.");
5238 return false;
5239 }
5240 PackageParser.Package p;
5241 boolean dataOnly = false;
5242 synchronized (mPackages) {
5243 p = mPackages.get(packageName);
5244 if(p == null) {
5245 dataOnly = true;
5246 PackageSetting ps = mSettings.mPackages.get(packageName);
5247 if((ps == null) || (ps.pkg == null)) {
5248 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5249 return false;
5250 }
5251 p = ps.pkg;
5252 }
5253 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005254 boolean useEncryptedFSDir = false;
5255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 if(!dataOnly) {
5257 //need to check this only for fully installed applications
5258 if (p == null) {
5259 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5260 return false;
5261 }
5262 final ApplicationInfo applicationInfo = p.applicationInfo;
5263 if (applicationInfo == null) {
5264 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5265 return false;
5266 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005267 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 }
5269 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005270 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 if (retCode < 0) {
5272 Log.w(TAG, "Couldn't remove cache files for package: "
5273 + packageName);
5274 return false;
5275 }
5276 }
5277 return true;
5278 }
5279
5280 public void deleteApplicationCacheFiles(final String packageName,
5281 final IPackageDataObserver observer) {
5282 mContext.enforceCallingOrSelfPermission(
5283 android.Manifest.permission.DELETE_CACHE_FILES, null);
5284 // Queue up an async operation since the package deletion may take a little while.
5285 mHandler.post(new Runnable() {
5286 public void run() {
5287 mHandler.removeCallbacks(this);
5288 final boolean succeded;
5289 synchronized (mInstallLock) {
5290 succeded = deleteApplicationCacheFilesLI(packageName);
5291 }
5292 if(observer != null) {
5293 try {
5294 observer.onRemoveCompleted(packageName, succeded);
5295 } catch (RemoteException e) {
5296 Log.i(TAG, "Observer no longer exists.");
5297 }
5298 } //end if observer
5299 } //end run
5300 });
5301 }
5302
5303 private boolean deleteApplicationCacheFilesLI(String packageName) {
5304 if (packageName == null) {
5305 Log.w(TAG, "Attempt to delete null packageName.");
5306 return false;
5307 }
5308 PackageParser.Package p;
5309 synchronized (mPackages) {
5310 p = mPackages.get(packageName);
5311 }
5312 if (p == null) {
5313 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5314 return false;
5315 }
5316 final ApplicationInfo applicationInfo = p.applicationInfo;
5317 if (applicationInfo == null) {
5318 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5319 return false;
5320 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005321 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005322 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005323 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 if (retCode < 0) {
5325 Log.w(TAG, "Couldn't remove cache files for package: "
5326 + packageName);
5327 return false;
5328 }
5329 }
5330 return true;
5331 }
5332
5333 public void getPackageSizeInfo(final String packageName,
5334 final IPackageStatsObserver observer) {
5335 mContext.enforceCallingOrSelfPermission(
5336 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5337 // Queue up an async operation since the package deletion may take a little while.
5338 mHandler.post(new Runnable() {
5339 public void run() {
5340 mHandler.removeCallbacks(this);
5341 PackageStats lStats = new PackageStats(packageName);
5342 final boolean succeded;
5343 synchronized (mInstallLock) {
5344 succeded = getPackageSizeInfoLI(packageName, lStats);
5345 }
5346 if(observer != null) {
5347 try {
5348 observer.onGetStatsCompleted(lStats, succeded);
5349 } catch (RemoteException e) {
5350 Log.i(TAG, "Observer no longer exists.");
5351 }
5352 } //end if observer
5353 } //end run
5354 });
5355 }
5356
5357 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5358 if (packageName == null) {
5359 Log.w(TAG, "Attempt to get size of null packageName.");
5360 return false;
5361 }
5362 PackageParser.Package p;
5363 boolean dataOnly = false;
5364 synchronized (mPackages) {
5365 p = mPackages.get(packageName);
5366 if(p == null) {
5367 dataOnly = true;
5368 PackageSetting ps = mSettings.mPackages.get(packageName);
5369 if((ps == null) || (ps.pkg == null)) {
5370 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5371 return false;
5372 }
5373 p = ps.pkg;
5374 }
5375 }
5376 String publicSrcDir = null;
5377 if(!dataOnly) {
5378 final ApplicationInfo applicationInfo = p.applicationInfo;
5379 if (applicationInfo == null) {
5380 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5381 return false;
5382 }
5383 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5384 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005385 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005386 if (mInstaller != null) {
5387 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005388 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 if (res < 0) {
5390 return false;
5391 } else {
5392 return true;
5393 }
5394 }
5395 return true;
5396 }
5397
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005399 public void addPackageToPreferred(String packageName) {
5400 mContext.enforceCallingOrSelfPermission(
5401 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005402 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 }
5404
5405 public void removePackageFromPreferred(String packageName) {
5406 mContext.enforceCallingOrSelfPermission(
5407 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005408 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 }
5410
5411 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005412 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 }
5414
5415 public void addPreferredActivity(IntentFilter filter, int match,
5416 ComponentName[] set, ComponentName activity) {
5417 mContext.enforceCallingOrSelfPermission(
5418 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5419
5420 synchronized (mPackages) {
5421 Log.i(TAG, "Adding preferred activity " + activity + ":");
5422 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5423 mSettings.mPreferredActivities.addFilter(
5424 new PreferredActivity(filter, match, set, activity));
5425 mSettings.writeLP();
5426 }
5427 }
5428
Satish Sampath8dbe6122009-06-02 23:35:54 +01005429 public void replacePreferredActivity(IntentFilter filter, int match,
5430 ComponentName[] set, ComponentName activity) {
5431 mContext.enforceCallingOrSelfPermission(
5432 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5433 if (filter.countActions() != 1) {
5434 throw new IllegalArgumentException(
5435 "replacePreferredActivity expects filter to have only 1 action.");
5436 }
5437 if (filter.countCategories() != 1) {
5438 throw new IllegalArgumentException(
5439 "replacePreferredActivity expects filter to have only 1 category.");
5440 }
5441 if (filter.countDataAuthorities() != 0
5442 || filter.countDataPaths() != 0
5443 || filter.countDataSchemes() != 0
5444 || filter.countDataTypes() != 0) {
5445 throw new IllegalArgumentException(
5446 "replacePreferredActivity expects filter to have no data authorities, " +
5447 "paths, schemes or types.");
5448 }
5449 synchronized (mPackages) {
5450 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5451 String action = filter.getAction(0);
5452 String category = filter.getCategory(0);
5453 while (it.hasNext()) {
5454 PreferredActivity pa = it.next();
5455 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5456 it.remove();
5457 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5458 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5459 }
5460 }
5461 addPreferredActivity(filter, match, set, activity);
5462 }
5463 }
5464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 public void clearPackagePreferredActivities(String packageName) {
5466 mContext.enforceCallingOrSelfPermission(
5467 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5468
5469 synchronized (mPackages) {
5470 if (clearPackagePreferredActivitiesLP(packageName)) {
5471 mSettings.writeLP();
5472 }
5473 }
5474 }
5475
5476 boolean clearPackagePreferredActivitiesLP(String packageName) {
5477 boolean changed = false;
5478 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5479 while (it.hasNext()) {
5480 PreferredActivity pa = it.next();
5481 if (pa.mActivity.getPackageName().equals(packageName)) {
5482 it.remove();
5483 changed = true;
5484 }
5485 }
5486 return changed;
5487 }
5488
5489 public int getPreferredActivities(List<IntentFilter> outFilters,
5490 List<ComponentName> outActivities, String packageName) {
5491
5492 int num = 0;
5493 synchronized (mPackages) {
5494 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5495 while (it.hasNext()) {
5496 PreferredActivity pa = it.next();
5497 if (packageName == null
5498 || pa.mActivity.getPackageName().equals(packageName)) {
5499 if (outFilters != null) {
5500 outFilters.add(new IntentFilter(pa));
5501 }
5502 if (outActivities != null) {
5503 outActivities.add(pa.mActivity);
5504 }
5505 }
5506 }
5507 }
5508
5509 return num;
5510 }
5511
5512 public void setApplicationEnabledSetting(String appPackageName,
5513 int newState, int flags) {
5514 setEnabledSetting(appPackageName, null, newState, flags);
5515 }
5516
5517 public void setComponentEnabledSetting(ComponentName componentName,
5518 int newState, int flags) {
5519 setEnabledSetting(componentName.getPackageName(),
5520 componentName.getClassName(), newState, flags);
5521 }
5522
5523 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005524 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5526 || newState == COMPONENT_ENABLED_STATE_ENABLED
5527 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5528 throw new IllegalArgumentException("Invalid new component state: "
5529 + newState);
5530 }
5531 PackageSetting pkgSetting;
5532 final int uid = Binder.getCallingUid();
5533 final int permission = mContext.checkCallingPermission(
5534 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5535 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005536 boolean sendNow = false;
5537 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005538 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005540 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005542 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005544 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005546 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 }
5548 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005549 "Unknown component: " + packageName
5550 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 }
5552 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5553 throw new SecurityException(
5554 "Permission Denial: attempt to change component state from pid="
5555 + Binder.getCallingPid()
5556 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5557 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005558 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 // We're dealing with an application/package level state change
5560 pkgSetting.enabled = newState;
5561 } else {
5562 // We're dealing with a component level state change
5563 switch (newState) {
5564 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005565 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 break;
5567 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005568 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 break;
5570 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005571 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 break;
5573 default:
5574 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005575 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 }
5577 }
5578 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005579 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005580 components = mPendingBroadcasts.get(packageName);
5581 boolean newPackage = components == null;
5582 if (newPackage) {
5583 components = new ArrayList<String>();
5584 }
5585 if (!components.contains(componentName)) {
5586 components.add(componentName);
5587 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005588 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5589 sendNow = true;
5590 // Purge entry from pending broadcast list if another one exists already
5591 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005592 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005593 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005594 if (newPackage) {
5595 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005596 }
5597 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5598 // Schedule a message
5599 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5600 }
5601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 long callingId = Binder.clearCallingIdentity();
5605 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005606 if (sendNow) {
5607 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005608 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 } finally {
5611 Binder.restoreCallingIdentity(callingId);
5612 }
5613 }
5614
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005615 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005616 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5617 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5618 + " components=" + componentNames);
5619 Bundle extras = new Bundle(4);
5620 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5621 String nameList[] = new String[componentNames.size()];
5622 componentNames.toArray(nameList);
5623 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005624 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5625 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005626 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005627 }
5628
Jacek Surazski65e13172009-04-28 15:26:38 +02005629 public String getInstallerPackageName(String packageName) {
5630 synchronized (mPackages) {
5631 PackageSetting pkg = mSettings.mPackages.get(packageName);
5632 if (pkg == null) {
5633 throw new IllegalArgumentException("Unknown package: " + packageName);
5634 }
5635 return pkg.installerPackageName;
5636 }
5637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 public int getApplicationEnabledSetting(String appPackageName) {
5640 synchronized (mPackages) {
5641 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5642 if (pkg == null) {
5643 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5644 }
5645 return pkg.enabled;
5646 }
5647 }
5648
5649 public int getComponentEnabledSetting(ComponentName componentName) {
5650 synchronized (mPackages) {
5651 final String packageNameStr = componentName.getPackageName();
5652 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5653 if (pkg == null) {
5654 throw new IllegalArgumentException("Unknown component: " + componentName);
5655 }
5656 final String classNameStr = componentName.getClassName();
5657 return pkg.currentEnabledStateLP(classNameStr);
5658 }
5659 }
5660
5661 public void enterSafeMode() {
5662 if (!mSystemReady) {
5663 mSafeMode = true;
5664 }
5665 }
5666
5667 public void systemReady() {
5668 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005669
5670 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005671 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005672 mContext.getContentResolver(),
5673 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005674 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005675 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005676 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 }
5679
5680 public boolean isSafeMode() {
5681 return mSafeMode;
5682 }
5683
5684 public boolean hasSystemUidErrors() {
5685 return mHasSystemUidErrors;
5686 }
5687
5688 static String arrayToString(int[] array) {
5689 StringBuffer buf = new StringBuffer(128);
5690 buf.append('[');
5691 if (array != null) {
5692 for (int i=0; i<array.length; i++) {
5693 if (i > 0) buf.append(", ");
5694 buf.append(array[i]);
5695 }
5696 }
5697 buf.append(']');
5698 return buf.toString();
5699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 @Override
5702 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5703 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5704 != PackageManager.PERMISSION_GRANTED) {
5705 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5706 + Binder.getCallingPid()
5707 + ", uid=" + Binder.getCallingUid()
5708 + " without permission "
5709 + android.Manifest.permission.DUMP);
5710 return;
5711 }
5712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 synchronized (mPackages) {
5714 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005715 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 pw.println(" ");
5717 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005718 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 pw.println(" ");
5720 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005721 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 pw.println(" ");
5723 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005724 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 pw.println("Permissions:");
5727 {
5728 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005729 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5730 pw.print(Integer.toHexString(System.identityHashCode(p)));
5731 pw.println("):");
5732 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5733 pw.print(" uid="); pw.print(p.uid);
5734 pw.print(" gids="); pw.print(arrayToString(p.gids));
5735 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 }
5737 }
5738 pw.println(" ");
5739 pw.println("Packages:");
5740 {
5741 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005742 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5743 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5744 pw.println("):");
5745 pw.print(" userId="); pw.print(ps.userId);
5746 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5747 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5748 pw.print(" pkg="); pw.println(ps.pkg);
5749 pw.print(" codePath="); pw.println(ps.codePathString);
5750 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005752 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005753 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005754 pw.print(" supportsScreens=[");
5755 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005756 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005757 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005758 if (!first) pw.print(", ");
5759 first = false;
5760 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005762 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005763 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005764 if (!first) pw.print(", ");
5765 first = false;
5766 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005768 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005769 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005770 if (!first) pw.print(", ");
5771 first = false;
5772 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005773 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005774 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005775 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005776 if (!first) pw.print(", ");
5777 first = false;
5778 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005780 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005781 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5782 if (!first) pw.print(", ");
5783 first = false;
5784 pw.print("anyDensity");
5785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005787 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005788 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5789 pw.print(" signatures="); pw.println(ps.signatures);
5790 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5791 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5792 pw.print(" installStatus="); pw.print(ps.installStatus);
5793 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005794 if (ps.disabledComponents.size() > 0) {
5795 pw.println(" disabledComponents:");
5796 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005797 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 }
5799 }
5800 if (ps.enabledComponents.size() > 0) {
5801 pw.println(" enabledComponents:");
5802 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005803 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 }
5805 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005806 if (ps.grantedPermissions.size() > 0) {
5807 pw.println(" grantedPermissions:");
5808 for (String s : ps.grantedPermissions) {
5809 pw.print(" "); pw.println(s);
5810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005812 if (ps.loadedPermissions.size() > 0) {
5813 pw.println(" loadedPermissions:");
5814 for (String s : ps.loadedPermissions) {
5815 pw.print(" "); pw.println(s);
5816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 }
5818 }
5819 }
5820 pw.println(" ");
5821 pw.println("Shared Users:");
5822 {
5823 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005824 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5825 pw.print(Integer.toHexString(System.identityHashCode(su)));
5826 pw.println("):");
5827 pw.print(" userId="); pw.print(su.userId);
5828 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 pw.println(" grantedPermissions:");
5830 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005831 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 }
5833 pw.println(" loadedPermissions:");
5834 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005835 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 }
5837 }
5838 }
5839 pw.println(" ");
5840 pw.println("Settings parse messages:");
5841 pw.println(mSettings.mReadMessages.toString());
5842 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005843
5844 synchronized (mProviders) {
5845 pw.println(" ");
5846 pw.println("Registered ContentProviders:");
5847 for (PackageParser.Provider p : mProviders.values()) {
5848 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5849 pw.println(p.toString());
5850 }
5851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 }
5853
5854 static final class BasePermission {
5855 final static int TYPE_NORMAL = 0;
5856 final static int TYPE_BUILTIN = 1;
5857 final static int TYPE_DYNAMIC = 2;
5858
5859 final String name;
5860 final String sourcePackage;
5861 final int type;
5862 PackageParser.Permission perm;
5863 PermissionInfo pendingInfo;
5864 int uid;
5865 int[] gids;
5866
5867 BasePermission(String _name, String _sourcePackage, int _type) {
5868 name = _name;
5869 sourcePackage = _sourcePackage;
5870 type = _type;
5871 }
5872 }
5873
5874 static class PackageSignatures {
5875 private Signature[] mSignatures;
5876
5877 PackageSignatures(Signature[] sigs) {
5878 assignSignatures(sigs);
5879 }
5880
5881 PackageSignatures() {
5882 }
5883
5884 void writeXml(XmlSerializer serializer, String tagName,
5885 ArrayList<Signature> pastSignatures) throws IOException {
5886 if (mSignatures == null) {
5887 return;
5888 }
5889 serializer.startTag(null, tagName);
5890 serializer.attribute(null, "count",
5891 Integer.toString(mSignatures.length));
5892 for (int i=0; i<mSignatures.length; i++) {
5893 serializer.startTag(null, "cert");
5894 final Signature sig = mSignatures[i];
5895 final int sigHash = sig.hashCode();
5896 final int numPast = pastSignatures.size();
5897 int j;
5898 for (j=0; j<numPast; j++) {
5899 Signature pastSig = pastSignatures.get(j);
5900 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5901 serializer.attribute(null, "index", Integer.toString(j));
5902 break;
5903 }
5904 }
5905 if (j >= numPast) {
5906 pastSignatures.add(sig);
5907 serializer.attribute(null, "index", Integer.toString(numPast));
5908 serializer.attribute(null, "key", sig.toCharsString());
5909 }
5910 serializer.endTag(null, "cert");
5911 }
5912 serializer.endTag(null, tagName);
5913 }
5914
5915 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5916 throws IOException, XmlPullParserException {
5917 String countStr = parser.getAttributeValue(null, "count");
5918 if (countStr == null) {
5919 reportSettingsProblem(Log.WARN,
5920 "Error in package manager settings: <signatures> has"
5921 + " no count at " + parser.getPositionDescription());
5922 XmlUtils.skipCurrentTag(parser);
5923 }
5924 final int count = Integer.parseInt(countStr);
5925 mSignatures = new Signature[count];
5926 int pos = 0;
5927
5928 int outerDepth = parser.getDepth();
5929 int type;
5930 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5931 && (type != XmlPullParser.END_TAG
5932 || parser.getDepth() > outerDepth)) {
5933 if (type == XmlPullParser.END_TAG
5934 || type == XmlPullParser.TEXT) {
5935 continue;
5936 }
5937
5938 String tagName = parser.getName();
5939 if (tagName.equals("cert")) {
5940 if (pos < count) {
5941 String index = parser.getAttributeValue(null, "index");
5942 if (index != null) {
5943 try {
5944 int idx = Integer.parseInt(index);
5945 String key = parser.getAttributeValue(null, "key");
5946 if (key == null) {
5947 if (idx >= 0 && idx < pastSignatures.size()) {
5948 Signature sig = pastSignatures.get(idx);
5949 if (sig != null) {
5950 mSignatures[pos] = pastSignatures.get(idx);
5951 pos++;
5952 } else {
5953 reportSettingsProblem(Log.WARN,
5954 "Error in package manager settings: <cert> "
5955 + "index " + index + " is not defined at "
5956 + parser.getPositionDescription());
5957 }
5958 } else {
5959 reportSettingsProblem(Log.WARN,
5960 "Error in package manager settings: <cert> "
5961 + "index " + index + " is out of bounds at "
5962 + parser.getPositionDescription());
5963 }
5964 } else {
5965 while (pastSignatures.size() <= idx) {
5966 pastSignatures.add(null);
5967 }
5968 Signature sig = new Signature(key);
5969 pastSignatures.set(idx, sig);
5970 mSignatures[pos] = sig;
5971 pos++;
5972 }
5973 } catch (NumberFormatException e) {
5974 reportSettingsProblem(Log.WARN,
5975 "Error in package manager settings: <cert> "
5976 + "index " + index + " is not a number at "
5977 + parser.getPositionDescription());
5978 }
5979 } else {
5980 reportSettingsProblem(Log.WARN,
5981 "Error in package manager settings: <cert> has"
5982 + " no index at " + parser.getPositionDescription());
5983 }
5984 } else {
5985 reportSettingsProblem(Log.WARN,
5986 "Error in package manager settings: too "
5987 + "many <cert> tags, expected " + count
5988 + " at " + parser.getPositionDescription());
5989 }
5990 } else {
5991 reportSettingsProblem(Log.WARN,
5992 "Unknown element under <cert>: "
5993 + parser.getName());
5994 }
5995 XmlUtils.skipCurrentTag(parser);
5996 }
5997
5998 if (pos < count) {
5999 // Should never happen -- there is an error in the written
6000 // settings -- but if it does we don't want to generate
6001 // a bad array.
6002 Signature[] newSigs = new Signature[pos];
6003 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6004 mSignatures = newSigs;
6005 }
6006 }
6007
6008 /**
6009 * If any of the given 'sigs' is contained in the existing signatures,
6010 * then completely replace the current signatures with the ones in
6011 * 'sigs'. This is used for updating an existing package to a newly
6012 * installed version.
6013 */
6014 boolean updateSignatures(Signature[] sigs, boolean update) {
6015 if (mSignatures == null) {
6016 if (update) {
6017 assignSignatures(sigs);
6018 }
6019 return true;
6020 }
6021 if (sigs == null) {
6022 return false;
6023 }
6024
6025 for (int i=0; i<sigs.length; i++) {
6026 Signature sig = sigs[i];
6027 for (int j=0; j<mSignatures.length; j++) {
6028 if (mSignatures[j].equals(sig)) {
6029 if (update) {
6030 assignSignatures(sigs);
6031 }
6032 return true;
6033 }
6034 }
6035 }
6036 return false;
6037 }
6038
6039 /**
6040 * If any of the given 'sigs' is contained in the existing signatures,
6041 * then add in any new signatures found in 'sigs'. This is used for
6042 * including a new package into an existing shared user id.
6043 */
6044 boolean mergeSignatures(Signature[] sigs, boolean update) {
6045 if (mSignatures == null) {
6046 if (update) {
6047 assignSignatures(sigs);
6048 }
6049 return true;
6050 }
6051 if (sigs == null) {
6052 return false;
6053 }
6054
6055 Signature[] added = null;
6056 int addedCount = 0;
6057 boolean haveMatch = false;
6058 for (int i=0; i<sigs.length; i++) {
6059 Signature sig = sigs[i];
6060 boolean found = false;
6061 for (int j=0; j<mSignatures.length; j++) {
6062 if (mSignatures[j].equals(sig)) {
6063 found = true;
6064 haveMatch = true;
6065 break;
6066 }
6067 }
6068
6069 if (!found) {
6070 if (added == null) {
6071 added = new Signature[sigs.length];
6072 }
6073 added[i] = sig;
6074 addedCount++;
6075 }
6076 }
6077
6078 if (!haveMatch) {
6079 // Nothing matched -- reject the new signatures.
6080 return false;
6081 }
6082 if (added == null) {
6083 // Completely matched -- nothing else to do.
6084 return true;
6085 }
6086
6087 // Add additional signatures in.
6088 if (update) {
6089 Signature[] total = new Signature[addedCount+mSignatures.length];
6090 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6091 int j = mSignatures.length;
6092 for (int i=0; i<added.length; i++) {
6093 if (added[i] != null) {
6094 total[j] = added[i];
6095 j++;
6096 }
6097 }
6098 mSignatures = total;
6099 }
6100 return true;
6101 }
6102
6103 private void assignSignatures(Signature[] sigs) {
6104 if (sigs == null) {
6105 mSignatures = null;
6106 return;
6107 }
6108 mSignatures = new Signature[sigs.length];
6109 for (int i=0; i<sigs.length; i++) {
6110 mSignatures[i] = sigs[i];
6111 }
6112 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 @Override
6115 public String toString() {
6116 StringBuffer buf = new StringBuffer(128);
6117 buf.append("PackageSignatures{");
6118 buf.append(Integer.toHexString(System.identityHashCode(this)));
6119 buf.append(" [");
6120 if (mSignatures != null) {
6121 for (int i=0; i<mSignatures.length; i++) {
6122 if (i > 0) buf.append(", ");
6123 buf.append(Integer.toHexString(
6124 System.identityHashCode(mSignatures[i])));
6125 }
6126 }
6127 buf.append("]}");
6128 return buf.toString();
6129 }
6130 }
6131
6132 static class PreferredActivity extends IntentFilter {
6133 final int mMatch;
6134 final String[] mSetPackages;
6135 final String[] mSetClasses;
6136 final String[] mSetComponents;
6137 final ComponentName mActivity;
6138 final String mShortActivity;
6139 String mParseError;
6140
6141 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6142 ComponentName activity) {
6143 super(filter);
6144 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6145 mActivity = activity;
6146 mShortActivity = activity.flattenToShortString();
6147 mParseError = null;
6148 if (set != null) {
6149 final int N = set.length;
6150 String[] myPackages = new String[N];
6151 String[] myClasses = new String[N];
6152 String[] myComponents = new String[N];
6153 for (int i=0; i<N; i++) {
6154 ComponentName cn = set[i];
6155 if (cn == null) {
6156 mSetPackages = null;
6157 mSetClasses = null;
6158 mSetComponents = null;
6159 return;
6160 }
6161 myPackages[i] = cn.getPackageName().intern();
6162 myClasses[i] = cn.getClassName().intern();
6163 myComponents[i] = cn.flattenToShortString().intern();
6164 }
6165 mSetPackages = myPackages;
6166 mSetClasses = myClasses;
6167 mSetComponents = myComponents;
6168 } else {
6169 mSetPackages = null;
6170 mSetClasses = null;
6171 mSetComponents = null;
6172 }
6173 }
6174
6175 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6176 IOException {
6177 mShortActivity = parser.getAttributeValue(null, "name");
6178 mActivity = ComponentName.unflattenFromString(mShortActivity);
6179 if (mActivity == null) {
6180 mParseError = "Bad activity name " + mShortActivity;
6181 }
6182 String matchStr = parser.getAttributeValue(null, "match");
6183 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6184 String setCountStr = parser.getAttributeValue(null, "set");
6185 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6186
6187 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6188 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6189 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6190
6191 int setPos = 0;
6192
6193 int outerDepth = parser.getDepth();
6194 int type;
6195 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6196 && (type != XmlPullParser.END_TAG
6197 || parser.getDepth() > outerDepth)) {
6198 if (type == XmlPullParser.END_TAG
6199 || type == XmlPullParser.TEXT) {
6200 continue;
6201 }
6202
6203 String tagName = parser.getName();
6204 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6205 // + parser.getDepth() + " tag=" + tagName);
6206 if (tagName.equals("set")) {
6207 String name = parser.getAttributeValue(null, "name");
6208 if (name == null) {
6209 if (mParseError == null) {
6210 mParseError = "No name in set tag in preferred activity "
6211 + mShortActivity;
6212 }
6213 } else if (setPos >= setCount) {
6214 if (mParseError == null) {
6215 mParseError = "Too many set tags in preferred activity "
6216 + mShortActivity;
6217 }
6218 } else {
6219 ComponentName cn = ComponentName.unflattenFromString(name);
6220 if (cn == null) {
6221 if (mParseError == null) {
6222 mParseError = "Bad set name " + name + " in preferred activity "
6223 + mShortActivity;
6224 }
6225 } else {
6226 myPackages[setPos] = cn.getPackageName();
6227 myClasses[setPos] = cn.getClassName();
6228 myComponents[setPos] = name;
6229 setPos++;
6230 }
6231 }
6232 XmlUtils.skipCurrentTag(parser);
6233 } else if (tagName.equals("filter")) {
6234 //Log.i(TAG, "Starting to parse filter...");
6235 readFromXml(parser);
6236 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6237 // + parser.getDepth() + " tag=" + parser.getName());
6238 } else {
6239 reportSettingsProblem(Log.WARN,
6240 "Unknown element under <preferred-activities>: "
6241 + parser.getName());
6242 XmlUtils.skipCurrentTag(parser);
6243 }
6244 }
6245
6246 if (setPos != setCount) {
6247 if (mParseError == null) {
6248 mParseError = "Not enough set tags (expected " + setCount
6249 + " but found " + setPos + ") in " + mShortActivity;
6250 }
6251 }
6252
6253 mSetPackages = myPackages;
6254 mSetClasses = myClasses;
6255 mSetComponents = myComponents;
6256 }
6257
6258 public void writeToXml(XmlSerializer serializer) throws IOException {
6259 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6260 serializer.attribute(null, "name", mShortActivity);
6261 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6262 serializer.attribute(null, "set", Integer.toString(NS));
6263 for (int s=0; s<NS; s++) {
6264 serializer.startTag(null, "set");
6265 serializer.attribute(null, "name", mSetComponents[s]);
6266 serializer.endTag(null, "set");
6267 }
6268 serializer.startTag(null, "filter");
6269 super.writeToXml(serializer);
6270 serializer.endTag(null, "filter");
6271 }
6272
6273 boolean sameSet(List<ResolveInfo> query, int priority) {
6274 if (mSetPackages == null) return false;
6275 final int NQ = query.size();
6276 final int NS = mSetPackages.length;
6277 int numMatch = 0;
6278 for (int i=0; i<NQ; i++) {
6279 ResolveInfo ri = query.get(i);
6280 if (ri.priority != priority) continue;
6281 ActivityInfo ai = ri.activityInfo;
6282 boolean good = false;
6283 for (int j=0; j<NS; j++) {
6284 if (mSetPackages[j].equals(ai.packageName)
6285 && mSetClasses[j].equals(ai.name)) {
6286 numMatch++;
6287 good = true;
6288 break;
6289 }
6290 }
6291 if (!good) return false;
6292 }
6293 return numMatch == NS;
6294 }
6295 }
6296
6297 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006298 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 HashSet<String> grantedPermissions = new HashSet<String>();
6301 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006306 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6307 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6308 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 }
6310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 /**
6313 * Settings base class for pending and resolved classes.
6314 */
6315 static class PackageSettingBase extends GrantedPermissions {
6316 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006317 File codePath;
6318 String codePathString;
6319 File resourcePath;
6320 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 private long timeStamp;
6322 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006323 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324
6325 PackageSignatures signatures = new PackageSignatures();
6326
6327 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 /* Explicitly disabled components */
6330 HashSet<String> disabledComponents = new HashSet<String>(0);
6331 /* Explicitly enabled components */
6332 HashSet<String> enabledComponents = new HashSet<String>(0);
6333 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6334 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006335
Jacek Surazski65e13172009-04-28 15:26:38 +02006336 /* package name of the app that installed this package */
6337 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338
6339 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006340 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 super(pkgFlags);
6342 this.name = name;
6343 this.codePath = codePath;
6344 this.codePathString = codePath.toString();
6345 this.resourcePath = resourcePath;
6346 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006347 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 }
6349
Jacek Surazski65e13172009-04-28 15:26:38 +02006350 public void setInstallerPackageName(String packageName) {
6351 installerPackageName = packageName;
6352 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006353
Jacek Surazski65e13172009-04-28 15:26:38 +02006354 String getInstallerPackageName() {
6355 return installerPackageName;
6356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 public void setInstallStatus(int newStatus) {
6359 installStatus = newStatus;
6360 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 public int getInstallStatus() {
6363 return installStatus;
6364 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 public void setTimeStamp(long newStamp) {
6367 if (newStamp != timeStamp) {
6368 timeStamp = newStamp;
6369 timeStampString = Long.toString(newStamp);
6370 }
6371 }
6372
6373 public void setTimeStamp(long newStamp, String newStampStr) {
6374 timeStamp = newStamp;
6375 timeStampString = newStampStr;
6376 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 public long getTimeStamp() {
6379 return timeStamp;
6380 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 public String getTimeStampStr() {
6383 return timeStampString;
6384 }
6385
6386 public void copyFrom(PackageSettingBase base) {
6387 grantedPermissions = base.grantedPermissions;
6388 gids = base.gids;
6389 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 timeStamp = base.timeStamp;
6392 timeStampString = base.timeStampString;
6393 signatures = base.signatures;
6394 permissionsFixed = base.permissionsFixed;
6395 disabledComponents = base.disabledComponents;
6396 enabledComponents = base.enabledComponents;
6397 enabled = base.enabled;
6398 installStatus = base.installStatus;
6399 }
6400
6401 void enableComponentLP(String componentClassName) {
6402 disabledComponents.remove(componentClassName);
6403 enabledComponents.add(componentClassName);
6404 }
6405
6406 void disableComponentLP(String componentClassName) {
6407 enabledComponents.remove(componentClassName);
6408 disabledComponents.add(componentClassName);
6409 }
6410
6411 void restoreComponentLP(String componentClassName) {
6412 enabledComponents.remove(componentClassName);
6413 disabledComponents.remove(componentClassName);
6414 }
6415
6416 int currentEnabledStateLP(String componentName) {
6417 if (enabledComponents.contains(componentName)) {
6418 return COMPONENT_ENABLED_STATE_ENABLED;
6419 } else if (disabledComponents.contains(componentName)) {
6420 return COMPONENT_ENABLED_STATE_DISABLED;
6421 } else {
6422 return COMPONENT_ENABLED_STATE_DEFAULT;
6423 }
6424 }
6425 }
6426
6427 /**
6428 * Settings data for a particular package we know about.
6429 */
6430 static final class PackageSetting extends PackageSettingBase {
6431 int userId;
6432 PackageParser.Package pkg;
6433 SharedUserSetting sharedUser;
6434
6435 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006436 int pVersionCode, int pkgFlags) {
6437 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 @Override
6441 public String toString() {
6442 return "PackageSetting{"
6443 + Integer.toHexString(System.identityHashCode(this))
6444 + " " + name + "/" + userId + "}";
6445 }
6446 }
6447
6448 /**
6449 * Settings data for a particular shared user ID we know about.
6450 */
6451 static final class SharedUserSetting extends GrantedPermissions {
6452 final String name;
6453 int userId;
6454 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6455 final PackageSignatures signatures = new PackageSignatures();
6456
6457 SharedUserSetting(String _name, int _pkgFlags) {
6458 super(_pkgFlags);
6459 name = _name;
6460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 @Override
6463 public String toString() {
6464 return "SharedUserSetting{"
6465 + Integer.toHexString(System.identityHashCode(this))
6466 + " " + name + "/" + userId + "}";
6467 }
6468 }
6469
6470 /**
6471 * Holds information about dynamic settings.
6472 */
6473 private static final class Settings {
6474 private final File mSettingsFilename;
6475 private final File mBackupSettingsFilename;
6476 private final HashMap<String, PackageSetting> mPackages =
6477 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 // List of replaced system applications
6479 final HashMap<String, PackageSetting> mDisabledSysPackages =
6480 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 // The user's preferred activities associated with particular intent
6483 // filters.
6484 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6485 new IntentResolver<PreferredActivity, PreferredActivity>() {
6486 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006487 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006489 out.print(prefix); out.print(
6490 Integer.toHexString(System.identityHashCode(filter)));
6491 out.print(' ');
6492 out.print(filter.mActivity.flattenToShortString());
6493 out.print(" match=0x");
6494 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006496 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006498 out.print(prefix); out.print(" ");
6499 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 }
6501 }
6502 }
6503 };
6504 private final HashMap<String, SharedUserSetting> mSharedUsers =
6505 new HashMap<String, SharedUserSetting>();
6506 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6507 private final SparseArray<Object> mOtherUserIds =
6508 new SparseArray<Object>();
6509
6510 // For reading/writing settings file.
6511 private final ArrayList<Signature> mPastSignatures =
6512 new ArrayList<Signature>();
6513
6514 // Mapping from permission names to info about them.
6515 final HashMap<String, BasePermission> mPermissions =
6516 new HashMap<String, BasePermission>();
6517
6518 // Mapping from permission tree names to info about them.
6519 final HashMap<String, BasePermission> mPermissionTrees =
6520 new HashMap<String, BasePermission>();
6521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 private final StringBuilder mReadMessages = new StringBuilder();
6523
6524 private static final class PendingPackage extends PackageSettingBase {
6525 final int sharedId;
6526
6527 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006528 int sharedId, int pVersionCode, int pkgFlags) {
6529 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 this.sharedId = sharedId;
6531 }
6532 }
6533 private final ArrayList<PendingPackage> mPendingPackages
6534 = new ArrayList<PendingPackage>();
6535
6536 Settings() {
6537 File dataDir = Environment.getDataDirectory();
6538 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006539 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6540 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006542 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 FileUtils.setPermissions(systemDir.toString(),
6544 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6545 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6546 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006547 FileUtils.setPermissions(systemSecureDir.toString(),
6548 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6549 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6550 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 mSettingsFilename = new File(systemDir, "packages.xml");
6552 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6553 }
6554
6555 PackageSetting getPackageLP(PackageParser.Package pkg,
6556 SharedUserSetting sharedUser, File codePath, File resourcePath,
6557 int pkgFlags, boolean create, boolean add) {
6558 final String name = pkg.packageName;
6559 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006560 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 return p;
6562 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006563
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006564 PackageSetting peekPackageLP(String name) {
6565 return mPackages.get(name);
6566 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 PackageSetting p = mPackages.get(name);
6568 if (p != null && p.codePath.getPath().equals(codePath)) {
6569 return p;
6570 }
6571 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006572 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 void setInstallStatus(String pkgName, int status) {
6576 PackageSetting p = mPackages.get(pkgName);
6577 if(p != null) {
6578 if(p.getInstallStatus() != status) {
6579 p.setInstallStatus(status);
6580 }
6581 }
6582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006583
Jacek Surazski65e13172009-04-28 15:26:38 +02006584 void setInstallerPackageName(String pkgName,
6585 String installerPkgName) {
6586 PackageSetting p = mPackages.get(pkgName);
6587 if(p != null) {
6588 p.setInstallerPackageName(installerPkgName);
6589 }
6590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006591
Jacek Surazski65e13172009-04-28 15:26:38 +02006592 String getInstallerPackageName(String pkgName) {
6593 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006594 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006595 }
6596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 int getInstallStatus(String pkgName) {
6598 PackageSetting p = mPackages.get(pkgName);
6599 if(p != null) {
6600 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 return -1;
6603 }
6604
6605 SharedUserSetting getSharedUserLP(String name,
6606 int pkgFlags, boolean create) {
6607 SharedUserSetting s = mSharedUsers.get(name);
6608 if (s == null) {
6609 if (!create) {
6610 return null;
6611 }
6612 s = new SharedUserSetting(name, pkgFlags);
6613 if (MULTIPLE_APPLICATION_UIDS) {
6614 s.userId = newUserIdLP(s);
6615 } else {
6616 s.userId = FIRST_APPLICATION_UID;
6617 }
6618 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6619 // < 0 means we couldn't assign a userid; fall out and return
6620 // s, which is currently null
6621 if (s.userId >= 0) {
6622 mSharedUsers.put(name, s);
6623 }
6624 }
6625
6626 return s;
6627 }
6628
6629 int disableSystemPackageLP(String name) {
6630 PackageSetting p = mPackages.get(name);
6631 if(p == null) {
6632 Log.w(TAG, "Package:"+name+" is not an installed package");
6633 return -1;
6634 }
6635 PackageSetting dp = mDisabledSysPackages.get(name);
6636 // always make sure the system package code and resource paths dont change
6637 if(dp == null) {
6638 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6639 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6640 }
6641 mDisabledSysPackages.put(name, p);
6642 }
6643 return removePackageLP(name);
6644 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 PackageSetting enableSystemPackageLP(String name) {
6647 PackageSetting p = mDisabledSysPackages.get(name);
6648 if(p == null) {
6649 Log.w(TAG, "Package:"+name+" is not disabled");
6650 return null;
6651 }
6652 // Reset flag in ApplicationInfo object
6653 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6654 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6655 }
6656 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006657 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 mDisabledSysPackages.remove(name);
6659 return ret;
6660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006663 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664 PackageSetting p = mPackages.get(name);
6665 if (p != null) {
6666 if (p.userId == uid) {
6667 return p;
6668 }
6669 reportSettingsProblem(Log.ERROR,
6670 "Adding duplicate package, keeping first: " + name);
6671 return null;
6672 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006673 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 p.userId = uid;
6675 if (addUserIdLP(uid, p, name)) {
6676 mPackages.put(name, p);
6677 return p;
6678 }
6679 return null;
6680 }
6681
6682 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6683 SharedUserSetting s = mSharedUsers.get(name);
6684 if (s != null) {
6685 if (s.userId == uid) {
6686 return s;
6687 }
6688 reportSettingsProblem(Log.ERROR,
6689 "Adding duplicate shared user, keeping first: " + name);
6690 return null;
6691 }
6692 s = new SharedUserSetting(name, pkgFlags);
6693 s.userId = uid;
6694 if (addUserIdLP(uid, s, name)) {
6695 mSharedUsers.put(name, s);
6696 return s;
6697 }
6698 return null;
6699 }
6700
6701 private PackageSetting getPackageLP(String name,
6702 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006703 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 PackageSetting p = mPackages.get(name);
6705 if (p != null) {
6706 if (!p.codePath.equals(codePath)) {
6707 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006708 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006709 // This is an updated system app with versions in both system
6710 // and data partition. Just let the most recent version
6711 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006712 Log.w(TAG, "Trying to update system app code path from " +
6713 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006714 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006715 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006716 reportSettingsProblem(Log.WARN,
6717 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006718 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006720 }
6721 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 reportSettingsProblem(Log.WARN,
6723 "Package " + name + " shared user changed from "
6724 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6725 + " to "
6726 + (sharedUser != null ? sharedUser.name : "<nothing>")
6727 + "; replacing with new");
6728 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006729 } else {
6730 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6731 // If what we are scanning is a system package, then
6732 // make it so, regardless of whether it was previously
6733 // installed only in the data partition.
6734 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 }
6737 }
6738 if (p == null) {
6739 // Create a new PackageSettings entry. this can end up here because
6740 // of code path mismatch or user id mismatch of an updated system partition
6741 if (!create) {
6742 return null;
6743 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006744 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006746 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 if (sharedUser != null) {
6748 p.userId = sharedUser.userId;
6749 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006750 // Clone the setting here for disabled system packages
6751 PackageSetting dis = mDisabledSysPackages.get(name);
6752 if (dis != null) {
6753 // For disabled packages a new setting is created
6754 // from the existing user id. This still has to be
6755 // added to list of user id's
6756 // Copy signatures from previous setting
6757 if (dis.signatures.mSignatures != null) {
6758 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6759 }
6760 p.userId = dis.userId;
6761 // Clone permissions
6762 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6763 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6764 // Clone component info
6765 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6766 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6767 // Add new setting to list of user ids
6768 addUserIdLP(p.userId, p, name);
6769 } else {
6770 // Assign new user id
6771 p.userId = newUserIdLP(p);
6772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 } else {
6774 p.userId = FIRST_APPLICATION_UID;
6775 }
6776 if (p.userId < 0) {
6777 reportSettingsProblem(Log.WARN,
6778 "Package " + name + " could not be assigned a valid uid");
6779 return null;
6780 }
6781 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006782 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006784 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 }
6786 }
6787 return p;
6788 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006789
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006790 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006791 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006792 String codePath = pkg.applicationInfo.sourceDir;
6793 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006794 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006795 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006796 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006797 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006798 p.codePath = new File(codePath);
6799 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006800 }
6801 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006802 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006803 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006804 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006805 p.resourcePath = new File(resourcePath);
6806 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006807 }
6808 // Update version code if needed
6809 if (pkg.mVersionCode != p.versionCode) {
6810 p.versionCode = pkg.mVersionCode;
6811 }
6812 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6813 }
6814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 // Utility method that adds a PackageSetting to mPackages and
6816 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006817 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 SharedUserSetting sharedUser) {
6819 mPackages.put(name, p);
6820 if (sharedUser != null) {
6821 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6822 reportSettingsProblem(Log.ERROR,
6823 "Package " + p.name + " was user "
6824 + p.sharedUser + " but is now " + sharedUser
6825 + "; I am not changing its files so it will probably fail!");
6826 p.sharedUser.packages.remove(p);
6827 } else if (p.userId != sharedUser.userId) {
6828 reportSettingsProblem(Log.ERROR,
6829 "Package " + p.name + " was user id " + p.userId
6830 + " but is now user " + sharedUser
6831 + " with id " + sharedUser.userId
6832 + "; I am not changing its files so it will probably fail!");
6833 }
6834
6835 sharedUser.packages.add(p);
6836 p.sharedUser = sharedUser;
6837 p.userId = sharedUser.userId;
6838 }
6839 }
6840
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006841 /*
6842 * Update the shared user setting when a package using
6843 * specifying the shared user id is removed. The gids
6844 * associated with each permission of the deleted package
6845 * are removed from the shared user's gid list only if its
6846 * not in use by other permissions of packages in the
6847 * shared user setting.
6848 */
6849 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6851 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6852 return;
6853 }
6854 // No sharedUserId
6855 if (deletedPs.sharedUser == null) {
6856 return;
6857 }
6858 SharedUserSetting sus = deletedPs.sharedUser;
6859 // Update permissions
6860 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6861 boolean used = false;
6862 if (!sus.grantedPermissions.contains (eachPerm)) {
6863 continue;
6864 }
6865 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006866 if (pkg.pkg != null &&
6867 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
6868 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006869 used = true;
6870 break;
6871 }
6872 }
6873 if (!used) {
6874 // can safely delete this permission from list
6875 sus.grantedPermissions.remove(eachPerm);
6876 sus.loadedPermissions.remove(eachPerm);
6877 }
6878 }
6879 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006880 int newGids[] = globalGids;
6881 for (String eachPerm : sus.grantedPermissions) {
6882 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07006883 if (bp != null) {
6884 newGids = appendInts(newGids, bp.gids);
6885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 }
6887 sus.gids = newGids;
6888 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006890 private int removePackageLP(String name) {
6891 PackageSetting p = mPackages.get(name);
6892 if (p != null) {
6893 mPackages.remove(name);
6894 if (p.sharedUser != null) {
6895 p.sharedUser.packages.remove(p);
6896 if (p.sharedUser.packages.size() == 0) {
6897 mSharedUsers.remove(p.sharedUser.name);
6898 removeUserIdLP(p.sharedUser.userId);
6899 return p.sharedUser.userId;
6900 }
6901 } else {
6902 removeUserIdLP(p.userId);
6903 return p.userId;
6904 }
6905 }
6906 return -1;
6907 }
6908
6909 private boolean addUserIdLP(int uid, Object obj, Object name) {
6910 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6911 return false;
6912 }
6913
6914 if (uid >= FIRST_APPLICATION_UID) {
6915 int N = mUserIds.size();
6916 final int index = uid - FIRST_APPLICATION_UID;
6917 while (index >= N) {
6918 mUserIds.add(null);
6919 N++;
6920 }
6921 if (mUserIds.get(index) != null) {
6922 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006923 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 + " name=" + name);
6925 return false;
6926 }
6927 mUserIds.set(index, obj);
6928 } else {
6929 if (mOtherUserIds.get(uid) != null) {
6930 reportSettingsProblem(Log.ERROR,
6931 "Adding duplicate shared id: " + uid
6932 + " name=" + name);
6933 return false;
6934 }
6935 mOtherUserIds.put(uid, obj);
6936 }
6937 return true;
6938 }
6939
6940 public Object getUserIdLP(int uid) {
6941 if (uid >= FIRST_APPLICATION_UID) {
6942 int N = mUserIds.size();
6943 final int index = uid - FIRST_APPLICATION_UID;
6944 return index < N ? mUserIds.get(index) : null;
6945 } else {
6946 return mOtherUserIds.get(uid);
6947 }
6948 }
6949
6950 private void removeUserIdLP(int uid) {
6951 if (uid >= FIRST_APPLICATION_UID) {
6952 int N = mUserIds.size();
6953 final int index = uid - FIRST_APPLICATION_UID;
6954 if (index < N) mUserIds.set(index, null);
6955 } else {
6956 mOtherUserIds.remove(uid);
6957 }
6958 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 void writeLP() {
6961 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6962
6963 // Keep the old settings around until we know the new ones have
6964 // been successfully written.
6965 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07006966 // Presence of backup settings file indicates that we failed
6967 // to persist settings earlier. So preserve the older
6968 // backup for future reference since the current settings
6969 // might have been corrupted.
6970 if (!mBackupSettingsFilename.exists()) {
6971 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6972 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6973 return;
6974 }
6975 } else {
6976 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 }
6979
6980 mPastSignatures.clear();
6981
6982 try {
6983 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6984
6985 //XmlSerializer serializer = XmlUtils.serializerInstance();
6986 XmlSerializer serializer = new FastXmlSerializer();
6987 serializer.setOutput(str, "utf-8");
6988 serializer.startDocument(null, true);
6989 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6990
6991 serializer.startTag(null, "packages");
6992
6993 serializer.startTag(null, "permission-trees");
6994 for (BasePermission bp : mPermissionTrees.values()) {
6995 writePermission(serializer, bp);
6996 }
6997 serializer.endTag(null, "permission-trees");
6998
6999 serializer.startTag(null, "permissions");
7000 for (BasePermission bp : mPermissions.values()) {
7001 writePermission(serializer, bp);
7002 }
7003 serializer.endTag(null, "permissions");
7004
7005 for (PackageSetting pkg : mPackages.values()) {
7006 writePackage(serializer, pkg);
7007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7010 writeDisabledSysPackage(serializer, pkg);
7011 }
7012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007013 serializer.startTag(null, "preferred-activities");
7014 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7015 serializer.startTag(null, "item");
7016 pa.writeToXml(serializer);
7017 serializer.endTag(null, "item");
7018 }
7019 serializer.endTag(null, "preferred-activities");
7020
7021 for (SharedUserSetting usr : mSharedUsers.values()) {
7022 serializer.startTag(null, "shared-user");
7023 serializer.attribute(null, "name", usr.name);
7024 serializer.attribute(null, "userId",
7025 Integer.toString(usr.userId));
7026 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7027 serializer.startTag(null, "perms");
7028 for (String name : usr.grantedPermissions) {
7029 serializer.startTag(null, "item");
7030 serializer.attribute(null, "name", name);
7031 serializer.endTag(null, "item");
7032 }
7033 serializer.endTag(null, "perms");
7034 serializer.endTag(null, "shared-user");
7035 }
7036
7037 serializer.endTag(null, "packages");
7038
7039 serializer.endDocument();
7040
7041 str.flush();
7042 str.close();
7043
7044 // New settings successfully written, old ones are no longer
7045 // needed.
7046 mBackupSettingsFilename.delete();
7047 FileUtils.setPermissions(mSettingsFilename.toString(),
7048 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7049 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7050 |FileUtils.S_IROTH,
7051 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007052 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053
7054 } catch(XmlPullParserException e) {
7055 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 -08007056 } catch(java.io.IOException e) {
7057 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 -08007058 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007059 // Clean up partially written file
7060 if (mSettingsFilename.exists()) {
7061 if (!mSettingsFilename.delete()) {
7062 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7063 }
7064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 //Debug.stopMethodTracing();
7066 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007067
7068 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007069 throws java.io.IOException {
7070 serializer.startTag(null, "updated-package");
7071 serializer.attribute(null, "name", pkg.name);
7072 serializer.attribute(null, "codePath", pkg.codePathString);
7073 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007074 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007075 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7076 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7077 }
7078 if (pkg.sharedUser == null) {
7079 serializer.attribute(null, "userId",
7080 Integer.toString(pkg.userId));
7081 } else {
7082 serializer.attribute(null, "sharedUserId",
7083 Integer.toString(pkg.userId));
7084 }
7085 serializer.startTag(null, "perms");
7086 if (pkg.sharedUser == null) {
7087 // If this is a shared user, the permissions will
7088 // be written there. We still need to write an
7089 // empty permissions list so permissionsFixed will
7090 // be set.
7091 for (final String name : pkg.grantedPermissions) {
7092 BasePermission bp = mPermissions.get(name);
7093 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7094 // We only need to write signature or system permissions but this wont
7095 // match the semantics of grantedPermissions. So write all permissions.
7096 serializer.startTag(null, "item");
7097 serializer.attribute(null, "name", name);
7098 serializer.endTag(null, "item");
7099 }
7100 }
7101 }
7102 serializer.endTag(null, "perms");
7103 serializer.endTag(null, "updated-package");
7104 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007105
7106 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 throws java.io.IOException {
7108 serializer.startTag(null, "package");
7109 serializer.attribute(null, "name", pkg.name);
7110 serializer.attribute(null, "codePath", pkg.codePathString);
7111 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7112 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7113 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007114 serializer.attribute(null, "flags",
7115 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007117 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 if (pkg.sharedUser == null) {
7119 serializer.attribute(null, "userId",
7120 Integer.toString(pkg.userId));
7121 } else {
7122 serializer.attribute(null, "sharedUserId",
7123 Integer.toString(pkg.userId));
7124 }
7125 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7126 serializer.attribute(null, "enabled",
7127 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7128 ? "true" : "false");
7129 }
7130 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7131 serializer.attribute(null, "installStatus", "false");
7132 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007133 if (pkg.installerPackageName != null) {
7134 serializer.attribute(null, "installer", pkg.installerPackageName);
7135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7137 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7138 serializer.startTag(null, "perms");
7139 if (pkg.sharedUser == null) {
7140 // If this is a shared user, the permissions will
7141 // be written there. We still need to write an
7142 // empty permissions list so permissionsFixed will
7143 // be set.
7144 for (final String name : pkg.grantedPermissions) {
7145 serializer.startTag(null, "item");
7146 serializer.attribute(null, "name", name);
7147 serializer.endTag(null, "item");
7148 }
7149 }
7150 serializer.endTag(null, "perms");
7151 }
7152 if (pkg.disabledComponents.size() > 0) {
7153 serializer.startTag(null, "disabled-components");
7154 for (final String name : pkg.disabledComponents) {
7155 serializer.startTag(null, "item");
7156 serializer.attribute(null, "name", name);
7157 serializer.endTag(null, "item");
7158 }
7159 serializer.endTag(null, "disabled-components");
7160 }
7161 if (pkg.enabledComponents.size() > 0) {
7162 serializer.startTag(null, "enabled-components");
7163 for (final String name : pkg.enabledComponents) {
7164 serializer.startTag(null, "item");
7165 serializer.attribute(null, "name", name);
7166 serializer.endTag(null, "item");
7167 }
7168 serializer.endTag(null, "enabled-components");
7169 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 serializer.endTag(null, "package");
7172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 void writePermission(XmlSerializer serializer, BasePermission bp)
7175 throws XmlPullParserException, java.io.IOException {
7176 if (bp.type != BasePermission.TYPE_BUILTIN
7177 && bp.sourcePackage != null) {
7178 serializer.startTag(null, "item");
7179 serializer.attribute(null, "name", bp.name);
7180 serializer.attribute(null, "package", bp.sourcePackage);
7181 if (DEBUG_SETTINGS) Log.v(TAG,
7182 "Writing perm: name=" + bp.name + " type=" + bp.type);
7183 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7184 PermissionInfo pi = bp.perm != null ? bp.perm.info
7185 : bp.pendingInfo;
7186 if (pi != null) {
7187 serializer.attribute(null, "type", "dynamic");
7188 if (pi.icon != 0) {
7189 serializer.attribute(null, "icon",
7190 Integer.toString(pi.icon));
7191 }
7192 if (pi.nonLocalizedLabel != null) {
7193 serializer.attribute(null, "label",
7194 pi.nonLocalizedLabel.toString());
7195 }
7196 if (pi.protectionLevel !=
7197 PermissionInfo.PROTECTION_NORMAL) {
7198 serializer.attribute(null, "protection",
7199 Integer.toString(pi.protectionLevel));
7200 }
7201 }
7202 }
7203 serializer.endTag(null, "item");
7204 }
7205 }
7206
7207 String getReadMessagesLP() {
7208 return mReadMessages.toString();
7209 }
7210
Oscar Montemayora8529f62009-11-18 10:14:20 -08007211 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7213 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007214 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 while(its.hasNext()) {
7216 String key = its.next();
7217 PackageSetting ps = mPackages.get(key);
7218 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007219 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 }
7221 }
7222 return ret;
7223 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007225 boolean readLP() {
7226 FileInputStream str = null;
7227 if (mBackupSettingsFilename.exists()) {
7228 try {
7229 str = new FileInputStream(mBackupSettingsFilename);
7230 mReadMessages.append("Reading from backup settings file\n");
7231 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007232 if (mSettingsFilename.exists()) {
7233 // If both the backup and settings file exist, we
7234 // ignore the settings since it might have been
7235 // corrupted.
7236 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7237 mSettingsFilename.delete();
7238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 } catch (java.io.IOException e) {
7240 // We'll try for the normal settings file.
7241 }
7242 }
7243
7244 mPastSignatures.clear();
7245
7246 try {
7247 if (str == null) {
7248 if (!mSettingsFilename.exists()) {
7249 mReadMessages.append("No settings file found\n");
7250 Log.i(TAG, "No current settings file!");
7251 return false;
7252 }
7253 str = new FileInputStream(mSettingsFilename);
7254 }
7255 XmlPullParser parser = Xml.newPullParser();
7256 parser.setInput(str, null);
7257
7258 int type;
7259 while ((type=parser.next()) != XmlPullParser.START_TAG
7260 && type != XmlPullParser.END_DOCUMENT) {
7261 ;
7262 }
7263
7264 if (type != XmlPullParser.START_TAG) {
7265 mReadMessages.append("No start tag found in settings file\n");
7266 Log.e(TAG, "No start tag found in package manager settings");
7267 return false;
7268 }
7269
7270 int outerDepth = parser.getDepth();
7271 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7272 && (type != XmlPullParser.END_TAG
7273 || parser.getDepth() > outerDepth)) {
7274 if (type == XmlPullParser.END_TAG
7275 || type == XmlPullParser.TEXT) {
7276 continue;
7277 }
7278
7279 String tagName = parser.getName();
7280 if (tagName.equals("package")) {
7281 readPackageLP(parser);
7282 } else if (tagName.equals("permissions")) {
7283 readPermissionsLP(mPermissions, parser);
7284 } else if (tagName.equals("permission-trees")) {
7285 readPermissionsLP(mPermissionTrees, parser);
7286 } else if (tagName.equals("shared-user")) {
7287 readSharedUserLP(parser);
7288 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007289 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 } else if (tagName.equals("preferred-activities")) {
7291 readPreferredActivitiesLP(parser);
7292 } else if(tagName.equals("updated-package")) {
7293 readDisabledSysPackageLP(parser);
7294 } else {
7295 Log.w(TAG, "Unknown element under <packages>: "
7296 + parser.getName());
7297 XmlUtils.skipCurrentTag(parser);
7298 }
7299 }
7300
7301 str.close();
7302
7303 } catch(XmlPullParserException e) {
7304 mReadMessages.append("Error reading: " + e.toString());
7305 Log.e(TAG, "Error reading package manager settings", e);
7306
7307 } catch(java.io.IOException e) {
7308 mReadMessages.append("Error reading: " + e.toString());
7309 Log.e(TAG, "Error reading package manager settings", e);
7310
7311 }
7312
7313 int N = mPendingPackages.size();
7314 for (int i=0; i<N; i++) {
7315 final PendingPackage pp = mPendingPackages.get(i);
7316 Object idObj = getUserIdLP(pp.sharedId);
7317 if (idObj != null && idObj instanceof SharedUserSetting) {
7318 PackageSetting p = getPackageLP(pp.name,
7319 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007320 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 if (p == null) {
7322 Log.w(TAG, "Unable to create application package for "
7323 + pp.name);
7324 continue;
7325 }
7326 p.copyFrom(pp);
7327 } else if (idObj != null) {
7328 String msg = "Bad package setting: package " + pp.name
7329 + " has shared uid " + pp.sharedId
7330 + " that is not a shared uid\n";
7331 mReadMessages.append(msg);
7332 Log.e(TAG, msg);
7333 } else {
7334 String msg = "Bad package setting: package " + pp.name
7335 + " has shared uid " + pp.sharedId
7336 + " that is not defined\n";
7337 mReadMessages.append(msg);
7338 Log.e(TAG, msg);
7339 }
7340 }
7341 mPendingPackages.clear();
7342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007343 mReadMessages.append("Read completed successfully: "
7344 + mPackages.size() + " packages, "
7345 + mSharedUsers.size() + " shared uids\n");
7346
7347 return true;
7348 }
7349
7350 private int readInt(XmlPullParser parser, String ns, String name,
7351 int defValue) {
7352 String v = parser.getAttributeValue(ns, name);
7353 try {
7354 if (v == null) {
7355 return defValue;
7356 }
7357 return Integer.parseInt(v);
7358 } catch (NumberFormatException e) {
7359 reportSettingsProblem(Log.WARN,
7360 "Error in package manager settings: attribute " +
7361 name + " has bad integer value " + v + " at "
7362 + parser.getPositionDescription());
7363 }
7364 return defValue;
7365 }
7366
7367 private void readPermissionsLP(HashMap<String, BasePermission> out,
7368 XmlPullParser parser)
7369 throws IOException, XmlPullParserException {
7370 int outerDepth = parser.getDepth();
7371 int type;
7372 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7373 && (type != XmlPullParser.END_TAG
7374 || parser.getDepth() > outerDepth)) {
7375 if (type == XmlPullParser.END_TAG
7376 || type == XmlPullParser.TEXT) {
7377 continue;
7378 }
7379
7380 String tagName = parser.getName();
7381 if (tagName.equals("item")) {
7382 String name = parser.getAttributeValue(null, "name");
7383 String sourcePackage = parser.getAttributeValue(null, "package");
7384 String ptype = parser.getAttributeValue(null, "type");
7385 if (name != null && sourcePackage != null) {
7386 boolean dynamic = "dynamic".equals(ptype);
7387 BasePermission bp = new BasePermission(name, sourcePackage,
7388 dynamic
7389 ? BasePermission.TYPE_DYNAMIC
7390 : BasePermission.TYPE_NORMAL);
7391 if (dynamic) {
7392 PermissionInfo pi = new PermissionInfo();
7393 pi.packageName = sourcePackage.intern();
7394 pi.name = name.intern();
7395 pi.icon = readInt(parser, null, "icon", 0);
7396 pi.nonLocalizedLabel = parser.getAttributeValue(
7397 null, "label");
7398 pi.protectionLevel = readInt(parser, null, "protection",
7399 PermissionInfo.PROTECTION_NORMAL);
7400 bp.pendingInfo = pi;
7401 }
7402 out.put(bp.name, bp);
7403 } else {
7404 reportSettingsProblem(Log.WARN,
7405 "Error in package manager settings: permissions has"
7406 + " no name at " + parser.getPositionDescription());
7407 }
7408 } else {
7409 reportSettingsProblem(Log.WARN,
7410 "Unknown element reading permissions: "
7411 + parser.getName() + " at "
7412 + parser.getPositionDescription());
7413 }
7414 XmlUtils.skipCurrentTag(parser);
7415 }
7416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 private void readDisabledSysPackageLP(XmlPullParser parser)
7419 throws XmlPullParserException, IOException {
7420 String name = parser.getAttributeValue(null, "name");
7421 String codePathStr = parser.getAttributeValue(null, "codePath");
7422 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
7423 if(resourcePathStr == null) {
7424 resourcePathStr = codePathStr;
7425 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007426 String version = parser.getAttributeValue(null, "version");
7427 int versionCode = 0;
7428 if (version != null) {
7429 try {
7430 versionCode = Integer.parseInt(version);
7431 } catch (NumberFormatException e) {
7432 }
7433 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 int pkgFlags = 0;
7436 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007437 PackageSetting ps = new PackageSetting(name,
7438 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007439 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 String timeStampStr = parser.getAttributeValue(null, "ts");
7441 if (timeStampStr != null) {
7442 try {
7443 long timeStamp = Long.parseLong(timeStampStr);
7444 ps.setTimeStamp(timeStamp, timeStampStr);
7445 } catch (NumberFormatException e) {
7446 }
7447 }
7448 String idStr = parser.getAttributeValue(null, "userId");
7449 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7450 if(ps.userId <= 0) {
7451 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7452 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7453 }
7454 int outerDepth = parser.getDepth();
7455 int type;
7456 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7457 && (type != XmlPullParser.END_TAG
7458 || parser.getDepth() > outerDepth)) {
7459 if (type == XmlPullParser.END_TAG
7460 || type == XmlPullParser.TEXT) {
7461 continue;
7462 }
7463
7464 String tagName = parser.getName();
7465 if (tagName.equals("perms")) {
7466 readGrantedPermissionsLP(parser,
7467 ps.grantedPermissions);
7468 } else {
7469 reportSettingsProblem(Log.WARN,
7470 "Unknown element under <updated-package>: "
7471 + parser.getName());
7472 XmlUtils.skipCurrentTag(parser);
7473 }
7474 }
7475 mDisabledSysPackages.put(name, ps);
7476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 private void readPackageLP(XmlPullParser parser)
7479 throws XmlPullParserException, IOException {
7480 String name = null;
7481 String idStr = null;
7482 String sharedIdStr = null;
7483 String codePathStr = null;
7484 String resourcePathStr = null;
7485 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007486 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487 int pkgFlags = 0;
7488 String timeStampStr;
7489 long timeStamp = 0;
7490 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007491 String version = null;
7492 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007493 try {
7494 name = parser.getAttributeValue(null, "name");
7495 idStr = parser.getAttributeValue(null, "userId");
7496 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7497 codePathStr = parser.getAttributeValue(null, "codePath");
7498 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007499 version = parser.getAttributeValue(null, "version");
7500 if (version != null) {
7501 try {
7502 versionCode = Integer.parseInt(version);
7503 } catch (NumberFormatException e) {
7504 }
7505 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007506 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007507
7508 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007510 try {
7511 pkgFlags = Integer.parseInt(systemStr);
7512 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007513 }
7514 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007515 // For backward compatibility
7516 systemStr = parser.getAttributeValue(null, "system");
7517 if (systemStr != null) {
7518 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
7519 } else {
7520 // Old settings that don't specify system... just treat
7521 // them as system, good enough.
7522 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 }
7525 timeStampStr = parser.getAttributeValue(null, "ts");
7526 if (timeStampStr != null) {
7527 try {
7528 timeStamp = Long.parseLong(timeStampStr);
7529 } catch (NumberFormatException e) {
7530 }
7531 }
7532 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7533 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7534 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7535 if (resourcePathStr == null) {
7536 resourcePathStr = codePathStr;
7537 }
7538 if (name == null) {
7539 reportSettingsProblem(Log.WARN,
7540 "Error in package manager settings: <package> has no name at "
7541 + parser.getPositionDescription());
7542 } else if (codePathStr == null) {
7543 reportSettingsProblem(Log.WARN,
7544 "Error in package manager settings: <package> has no codePath at "
7545 + parser.getPositionDescription());
7546 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007547 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007548 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7550 + ": userId=" + userId + " pkg=" + packageSetting);
7551 if (packageSetting == null) {
7552 reportSettingsProblem(Log.ERROR,
7553 "Failure adding uid " + userId
7554 + " while parsing settings at "
7555 + parser.getPositionDescription());
7556 } else {
7557 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7558 }
7559 } else if (sharedIdStr != null) {
7560 userId = sharedIdStr != null
7561 ? Integer.parseInt(sharedIdStr) : 0;
7562 if (userId > 0) {
7563 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007564 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7566 mPendingPackages.add((PendingPackage) packageSetting);
7567 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7568 + ": sharedUserId=" + userId + " pkg="
7569 + packageSetting);
7570 } else {
7571 reportSettingsProblem(Log.WARN,
7572 "Error in package manager settings: package "
7573 + name + " has bad sharedId " + sharedIdStr
7574 + " at " + parser.getPositionDescription());
7575 }
7576 } else {
7577 reportSettingsProblem(Log.WARN,
7578 "Error in package manager settings: package "
7579 + name + " has bad userId " + idStr + " at "
7580 + parser.getPositionDescription());
7581 }
7582 } catch (NumberFormatException e) {
7583 reportSettingsProblem(Log.WARN,
7584 "Error in package manager settings: package "
7585 + name + " has bad userId " + idStr + " at "
7586 + parser.getPositionDescription());
7587 }
7588 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007589 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 final String enabledStr = parser.getAttributeValue(null, "enabled");
7591 if (enabledStr != null) {
7592 if (enabledStr.equalsIgnoreCase("true")) {
7593 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7594 } else if (enabledStr.equalsIgnoreCase("false")) {
7595 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7596 } else if (enabledStr.equalsIgnoreCase("default")) {
7597 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7598 } else {
7599 reportSettingsProblem(Log.WARN,
7600 "Error in package manager settings: package "
7601 + name + " has bad enabled value: " + idStr
7602 + " at " + parser.getPositionDescription());
7603 }
7604 } else {
7605 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7606 }
7607 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7608 if (installStatusStr != null) {
7609 if (installStatusStr.equalsIgnoreCase("false")) {
7610 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7611 } else {
7612 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7613 }
7614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 int outerDepth = parser.getDepth();
7617 int type;
7618 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7619 && (type != XmlPullParser.END_TAG
7620 || parser.getDepth() > outerDepth)) {
7621 if (type == XmlPullParser.END_TAG
7622 || type == XmlPullParser.TEXT) {
7623 continue;
7624 }
7625
7626 String tagName = parser.getName();
7627 if (tagName.equals("disabled-components")) {
7628 readDisabledComponentsLP(packageSetting, parser);
7629 } else if (tagName.equals("enabled-components")) {
7630 readEnabledComponentsLP(packageSetting, parser);
7631 } else if (tagName.equals("sigs")) {
7632 packageSetting.signatures.readXml(parser, mPastSignatures);
7633 } else if (tagName.equals("perms")) {
7634 readGrantedPermissionsLP(parser,
7635 packageSetting.loadedPermissions);
7636 packageSetting.permissionsFixed = true;
7637 } else {
7638 reportSettingsProblem(Log.WARN,
7639 "Unknown element under <package>: "
7640 + parser.getName());
7641 XmlUtils.skipCurrentTag(parser);
7642 }
7643 }
7644 } else {
7645 XmlUtils.skipCurrentTag(parser);
7646 }
7647 }
7648
7649 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7650 XmlPullParser parser)
7651 throws IOException, XmlPullParserException {
7652 int outerDepth = parser.getDepth();
7653 int type;
7654 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7655 && (type != XmlPullParser.END_TAG
7656 || parser.getDepth() > outerDepth)) {
7657 if (type == XmlPullParser.END_TAG
7658 || type == XmlPullParser.TEXT) {
7659 continue;
7660 }
7661
7662 String tagName = parser.getName();
7663 if (tagName.equals("item")) {
7664 String name = parser.getAttributeValue(null, "name");
7665 if (name != null) {
7666 packageSetting.disabledComponents.add(name.intern());
7667 } else {
7668 reportSettingsProblem(Log.WARN,
7669 "Error in package manager settings: <disabled-components> has"
7670 + " no name at " + parser.getPositionDescription());
7671 }
7672 } else {
7673 reportSettingsProblem(Log.WARN,
7674 "Unknown element under <disabled-components>: "
7675 + parser.getName());
7676 }
7677 XmlUtils.skipCurrentTag(parser);
7678 }
7679 }
7680
7681 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7682 XmlPullParser parser)
7683 throws IOException, XmlPullParserException {
7684 int outerDepth = parser.getDepth();
7685 int type;
7686 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7687 && (type != XmlPullParser.END_TAG
7688 || parser.getDepth() > outerDepth)) {
7689 if (type == XmlPullParser.END_TAG
7690 || type == XmlPullParser.TEXT) {
7691 continue;
7692 }
7693
7694 String tagName = parser.getName();
7695 if (tagName.equals("item")) {
7696 String name = parser.getAttributeValue(null, "name");
7697 if (name != null) {
7698 packageSetting.enabledComponents.add(name.intern());
7699 } else {
7700 reportSettingsProblem(Log.WARN,
7701 "Error in package manager settings: <enabled-components> has"
7702 + " no name at " + parser.getPositionDescription());
7703 }
7704 } else {
7705 reportSettingsProblem(Log.WARN,
7706 "Unknown element under <enabled-components>: "
7707 + parser.getName());
7708 }
7709 XmlUtils.skipCurrentTag(parser);
7710 }
7711 }
7712
7713 private void readSharedUserLP(XmlPullParser parser)
7714 throws XmlPullParserException, IOException {
7715 String name = null;
7716 String idStr = null;
7717 int pkgFlags = 0;
7718 SharedUserSetting su = null;
7719 try {
7720 name = parser.getAttributeValue(null, "name");
7721 idStr = parser.getAttributeValue(null, "userId");
7722 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7723 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7724 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7725 }
7726 if (name == null) {
7727 reportSettingsProblem(Log.WARN,
7728 "Error in package manager settings: <shared-user> has no name at "
7729 + parser.getPositionDescription());
7730 } else if (userId == 0) {
7731 reportSettingsProblem(Log.WARN,
7732 "Error in package manager settings: shared-user "
7733 + name + " has bad userId " + idStr + " at "
7734 + parser.getPositionDescription());
7735 } else {
7736 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7737 reportSettingsProblem(Log.ERROR,
7738 "Occurred while parsing settings at "
7739 + parser.getPositionDescription());
7740 }
7741 }
7742 } catch (NumberFormatException e) {
7743 reportSettingsProblem(Log.WARN,
7744 "Error in package manager settings: package "
7745 + name + " has bad userId " + idStr + " at "
7746 + parser.getPositionDescription());
7747 };
7748
7749 if (su != null) {
7750 int outerDepth = parser.getDepth();
7751 int type;
7752 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7753 && (type != XmlPullParser.END_TAG
7754 || parser.getDepth() > outerDepth)) {
7755 if (type == XmlPullParser.END_TAG
7756 || type == XmlPullParser.TEXT) {
7757 continue;
7758 }
7759
7760 String tagName = parser.getName();
7761 if (tagName.equals("sigs")) {
7762 su.signatures.readXml(parser, mPastSignatures);
7763 } else if (tagName.equals("perms")) {
7764 readGrantedPermissionsLP(parser, su.loadedPermissions);
7765 } else {
7766 reportSettingsProblem(Log.WARN,
7767 "Unknown element under <shared-user>: "
7768 + parser.getName());
7769 XmlUtils.skipCurrentTag(parser);
7770 }
7771 }
7772
7773 } else {
7774 XmlUtils.skipCurrentTag(parser);
7775 }
7776 }
7777
7778 private void readGrantedPermissionsLP(XmlPullParser parser,
7779 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7780 int outerDepth = parser.getDepth();
7781 int type;
7782 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7783 && (type != XmlPullParser.END_TAG
7784 || parser.getDepth() > outerDepth)) {
7785 if (type == XmlPullParser.END_TAG
7786 || type == XmlPullParser.TEXT) {
7787 continue;
7788 }
7789
7790 String tagName = parser.getName();
7791 if (tagName.equals("item")) {
7792 String name = parser.getAttributeValue(null, "name");
7793 if (name != null) {
7794 outPerms.add(name.intern());
7795 } else {
7796 reportSettingsProblem(Log.WARN,
7797 "Error in package manager settings: <perms> has"
7798 + " no name at " + parser.getPositionDescription());
7799 }
7800 } else {
7801 reportSettingsProblem(Log.WARN,
7802 "Unknown element under <perms>: "
7803 + parser.getName());
7804 }
7805 XmlUtils.skipCurrentTag(parser);
7806 }
7807 }
7808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 private void readPreferredActivitiesLP(XmlPullParser parser)
7810 throws XmlPullParserException, IOException {
7811 int outerDepth = parser.getDepth();
7812 int type;
7813 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7814 && (type != XmlPullParser.END_TAG
7815 || parser.getDepth() > outerDepth)) {
7816 if (type == XmlPullParser.END_TAG
7817 || type == XmlPullParser.TEXT) {
7818 continue;
7819 }
7820
7821 String tagName = parser.getName();
7822 if (tagName.equals("item")) {
7823 PreferredActivity pa = new PreferredActivity(parser);
7824 if (pa.mParseError == null) {
7825 mPreferredActivities.addFilter(pa);
7826 } else {
7827 reportSettingsProblem(Log.WARN,
7828 "Error in package manager settings: <preferred-activity> "
7829 + pa.mParseError + " at "
7830 + parser.getPositionDescription());
7831 }
7832 } else {
7833 reportSettingsProblem(Log.WARN,
7834 "Unknown element under <preferred-activities>: "
7835 + parser.getName());
7836 XmlUtils.skipCurrentTag(parser);
7837 }
7838 }
7839 }
7840
7841 // Returns -1 if we could not find an available UserId to assign
7842 private int newUserIdLP(Object obj) {
7843 // Let's be stupidly inefficient for now...
7844 final int N = mUserIds.size();
7845 for (int i=0; i<N; i++) {
7846 if (mUserIds.get(i) == null) {
7847 mUserIds.set(i, obj);
7848 return FIRST_APPLICATION_UID + i;
7849 }
7850 }
7851
7852 // None left?
7853 if (N >= MAX_APPLICATION_UIDS) {
7854 return -1;
7855 }
7856
7857 mUserIds.add(obj);
7858 return FIRST_APPLICATION_UID + N;
7859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 public PackageSetting getDisabledSystemPkg(String name) {
7862 synchronized(mPackages) {
7863 PackageSetting ps = mDisabledSysPackages.get(name);
7864 return ps;
7865 }
7866 }
7867
7868 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7869 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7870 if (Config.LOGV) {
7871 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7872 + " componentName = " + componentInfo.name);
7873 Log.v(TAG, "enabledComponents: "
7874 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7875 Log.v(TAG, "disabledComponents: "
7876 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7877 }
7878 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7879 || ((componentInfo.enabled
7880 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7881 || (componentInfo.applicationInfo.enabled
7882 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7883 && !packageSettings.disabledComponents.contains(componentInfo.name))
7884 || packageSettings.enabledComponents.contains(componentInfo.name));
7885 }
7886 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007887
7888 // ------- apps on sdcard specific code -------
7889 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08007890 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08007891 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007892 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007893 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007894
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007895
7896 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007897 return (MountService) ServiceManager.getService("mount");
7898 }
7899
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007900 private String getEncryptKey() {
7901 try {
7902 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7903 if (sdEncKey == null) {
7904 sdEncKey = SystemKeyStore.getInstance().
7905 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
7906 if (sdEncKey == null) {
7907 Log.e(TAG, "Failed to create encryption keys");
7908 return null;
7909 }
7910 }
7911 return sdEncKey;
7912 } catch (NoSuchAlgorithmException nsae) {
7913 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
7914 return null;
7915 }
7916 }
7917
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007918 private String createSdDir(File tmpPackageFile, String pkgName) {
7919 // Create mount point via MountService
7920 MountService mountService = getMountService();
7921 long len = tmpPackageFile.length();
7922 int mbLen = (int) (len/(1024*1024));
7923 if ((len - (mbLen * 1024 * 1024)) > 0) {
7924 mbLen++;
7925 }
7926 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
7927 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08007928 String sdEncKey;
7929 try {
7930 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7931 if (sdEncKey == null) {
7932 sdEncKey = SystemKeyStore.getInstance().
7933 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
7934 if (sdEncKey == null) {
7935 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
7936 return null;
7937 }
7938 }
7939 } catch (NoSuchAlgorithmException nsae) {
7940 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
7941 return null;
7942 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007943 try {
7944 cachePath = mountService.createSecureContainer(pkgName,
7945 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007946 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007947 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
7948 return cachePath;
7949 } catch(IllegalStateException e) {
7950 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7951 }
7952 // TODO just fail here and let the user delete later on.
7953 try {
7954 mountService.destroySecureContainer(pkgName);
7955 if (DEBUG_SD_INSTALL) Log.i(TAG, "Destroying cache for " + pkgName + ", cachePath =" + cachePath);
7956 } catch(IllegalStateException e) {
7957 Log.e(TAG, "Failed to destroy existing cache: " + e);
7958 return null;
7959 }
7960 try {
7961 cachePath = mountService.createSecureContainer(pkgName,
7962 mbLen,
Oscar Montemayord02546b2010-01-14 16:38:40 -08007963 "vfat", sdEncKey, Process.SYSTEM_UID);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007964 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install again " + pkgName + ", cachePath =" + cachePath);
7965 return cachePath;
7966 } catch(IllegalStateException e) {
7967 Log.e(TAG, "Failed to create storage on sdcard with exception: " + e);
7968 return null;
7969 }
7970 }
7971
7972 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007973 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
7974 if (sdEncKey == null) {
7975 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
7976 return null;
7977 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007978 try {
Oscar Montemayord02546b2010-01-14 16:38:40 -08007979 return getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007980 } catch (IllegalStateException e) {
7981 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " exception : " + e);
7982 }
7983 return null;
7984 }
7985
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007986 private boolean unMountSdDir(String pkgName) {
7987 // STOPSHIP unmount directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08007988 try {
7989 getMountService().unmountSecureContainer(pkgName);
7990 return true;
7991 } catch (IllegalStateException e) {
7992 Log.e(TAG, "Failed to unmount : " + pkgName + " with exception " + e);
7993 }
7994 return false;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007995 }
7996
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007997 private String getSdDir(String pkgName) {
7998 String cachePath = null;
7999 try {
8000 cachePath = getMountService().getSecureContainerPath(pkgName);
8001 } catch (IllegalStateException e) {
8002 Log.e(TAG, "Failed to retrieve secure container path for pkg : " + pkgName + " with exception " + e);
8003 }
8004 return cachePath;
8005 }
8006
8007 private boolean finalizeSdDir(String pkgName) {
8008 try {
8009 getMountService().finalizeSecureContainer(pkgName);
8010 return true;
8011 } catch (IllegalStateException e) {
8012 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8013 return false;
8014 }
8015 }
8016
8017 private boolean destroySdDir(String pkgName) {
8018 try {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008019 // We need to destroy right away
8020 getMountService().destroySecureContainer(pkgName);
8021 return true;
8022 } catch (IllegalStateException e) {
8023 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8024 return false;
8025 }
8026 }
8027
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008028 static String[] getSecureContainerList() {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008029 try {
8030 return getMountService().getSecureContainerList();
8031 } catch (IllegalStateException e) {
8032 Log.i(TAG, "Failed to getSecureContainerList");
8033 }
8034 return null;
8035 }
8036
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008037 static String getTempContainerId() {
8038 String prefix = "smdl1tmp";
8039 int tmpIdx = 1;
8040 String list[] = getSecureContainerList();
8041 if (list != null) {
8042 int idx = 0;
8043 int idList[] = new int[MAX_CONTAINERS];
8044 boolean neverFound = true;
8045 for (String name : list) {
8046 // Ignore null entries
8047 if (name == null) {
8048 continue;
8049 }
8050 int sidx = name.indexOf(prefix);
8051 if (sidx == -1) {
8052 // Not a temp file. just ignore
8053 continue;
8054 }
8055 String subStr = name.substring(sidx + prefix.length());
8056 idList[idx] = -1;
8057 if (subStr != null) {
8058 try {
8059 int cid = Integer.parseInt(subStr);
8060 idList[idx++] = cid;
8061 neverFound = false;
8062 } catch (NumberFormatException e) {
8063 }
8064 }
8065 }
8066 if (!neverFound) {
8067 // Sort idList
8068 Arrays.sort(idList);
8069 for (int j = 1; j <= idList.length; j++) {
8070 if (idList[j-1] != j) {
8071 tmpIdx = j;
8072 break;
8073 }
8074 }
8075 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008076 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008077 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008078 }
8079
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008080 public void updateExternalMediaStatus(final boolean mediaStatus) {
8081 if (mediaStatus == mMediaMounted) {
8082 return;
8083 }
8084 mMediaMounted = mediaStatus;
8085 // Queue up an async operation since the package installation may take a little while.
8086 mHandler.post(new Runnable() {
8087 public void run() {
8088 mHandler.removeCallbacks(this);
8089 final String list[] = getSecureContainerList();
8090 if (list == null || list.length == 0) {
8091 return;
8092 }
8093 for (int i = 0; i < list.length; i++) {
8094 String mountPkg = list[i];
8095 // TODO compare with default package
8096 synchronized (mPackages) {
8097 PackageSetting ps = mSettings.mPackages.get(mountPkg);
8098 if (ps != null && (ps.pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) != 0) {
8099 if (mediaStatus) {
8100 String pkgPath = getSdDir(mountPkg);
8101 if (pkgPath == null) {
8102 continue;
8103 }
8104 pkgPath = ps.codePathString;
8105 int parseFlags = PackageParser.PARSE_CHATTY |
8106 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8107 PackageParser pp = new PackageParser(pkgPath);
8108 pp.setSeparateProcesses(mSeparateProcesses);
8109 final PackageParser.Package pkg = pp.parsePackage(new File(pkgPath),
8110 null, mMetrics, parseFlags);
8111 if (pkg == null) {
8112 Log.w(TAG, "Failed to install package : " + mountPkg + " from sd card");
8113 continue;
8114 }
8115 int scanMode = SCAN_MONITOR;
8116 // Scan the package
8117 if (scanPackageLI(pkg, parseFlags, scanMode) != null) {
8118 // Grant permissions
8119 grantPermissionsLP(pkg, false);
8120 // Persist settings
8121 mSettings.writeLP();
8122 } else {
8123 Log.i(TAG, "Failed to install package: " + mountPkg + " from sdcard");
8124 }
8125 } else {
8126 // Delete package
8127 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8128 boolean res = deletePackageLI(mountPkg, false, PackageManager.DONT_DELETE_DATA, outInfo);
8129 if (!res) {
8130 Log.e(TAG, "Failed to delete pkg from sdcard : " + mountPkg);
8131 }
8132 }
8133 }
8134 }
8135 }
8136 }
8137 });
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139}