Search in sources :

Example 1 with IApplicationThread

use of android.app.IApplicationThread in project android_frameworks_base by ParanoidAndroid.

the class ActivityManagerService method getTasks.

// =========================================================
// TASK MANAGEMENT
// =========================================================
public List getTasks(int maxNum, int flags, IThumbnailReceiver receiver) {
    ArrayList list = new ArrayList();
    PendingThumbnailsRecord pending = null;
    IApplicationThread topThumbnail = null;
    ActivityRecord topRecord = null;
    synchronized (this) {
        if (localLOGV)
            Slog.v(TAG, "getTasks: max=" + maxNum + ", flags=" + flags + ", receiver=" + receiver);
        if (checkCallingPermission(android.Manifest.permission.GET_TASKS) != PackageManager.PERMISSION_GRANTED) {
            if (receiver != null) {
                // it ain't gonna get them.
                try {
                    receiver.finished();
                } catch (RemoteException ex) {
                }
            }
            String msg = "Permission Denial: getTasks() from pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() + " requires " + android.Manifest.permission.GET_TASKS;
            Slog.w(TAG, msg);
            throw new SecurityException(msg);
        }
        int pos = mMainStack.mHistory.size() - 1;
        ActivityRecord next = pos >= 0 ? (ActivityRecord) mMainStack.mHistory.get(pos) : null;
        ActivityRecord top = null;
        TaskRecord curTask = null;
        int numActivities = 0;
        int numRunning = 0;
        while (pos >= 0 && maxNum > 0) {
            final ActivityRecord r = next;
            pos--;
            next = pos >= 0 ? (ActivityRecord) mMainStack.mHistory.get(pos) : null;
            // Initialize state for next task if needed.
            if (top == null || (top.state == ActivityState.INITIALIZING && top.task == r.task)) {
                top = r;
                curTask = r.task;
                numActivities = numRunning = 0;
            }
            // Add 'r' into the current task.
            numActivities++;
            if (r.app != null && r.app.thread != null) {
                numRunning++;
            }
            if (localLOGV)
                Slog.v(TAG, r.intent.getComponent().flattenToShortString() + ": task=" + r.task);
            // TaskInfo entry for what we have.
            if (next == null || next.task != curTask) {
                ActivityManager.RunningTaskInfo ci = new ActivityManager.RunningTaskInfo();
                ci.id = curTask.taskId;
                ci.baseActivity = r.intent.getComponent();
                ci.topActivity = top.intent.getComponent();
                if (top.thumbHolder != null) {
                    ci.description = top.thumbHolder.lastDescription;
                }
                ci.numActivities = numActivities;
                ci.numRunning = numRunning;
                //    "#" + maxNum + ": " + " descr=" + ci.description);
                if (ci.thumbnail == null && receiver != null) {
                    if (localLOGV)
                        Slog.v(TAG, "State=" + top.state + "Idle=" + top.idle + " app=" + top.app + " thr=" + (top.app != null ? top.app.thread : null));
                    if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
                        if (top.idle && top.app != null && top.app.thread != null) {
                            topRecord = top;
                            topThumbnail = top.app.thread;
                        } else {
                            top.thumbnailNeeded = true;
                        }
                    }
                    if (pending == null) {
                        pending = new PendingThumbnailsRecord(receiver);
                    }
                    pending.pendingRecords.add(top);
                }
                list.add(ci);
                maxNum--;
                top = null;
            }
        }
        if (pending != null) {
            mPendingThumbnails.add(pending);
        }
    }
    if (localLOGV)
        Slog.v(TAG, "We have pending thumbnails: " + pending);
    if (topThumbnail != null) {
        if (localLOGV)
            Slog.v(TAG, "Requesting top thumbnail");
        try {
            topThumbnail.requestThumbnail(topRecord.appToken);
        } catch (Exception e) {
            Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
            sendPendingThumbnail(null, topRecord.appToken, null, null, true);
        }
    }
    if (pending == null && receiver != null) {
        // activity should never have a canned thumbnail!  Oh well.
        try {
            receiver.finished();
        } catch (RemoteException ex) {
        }
    }
    return list;
}
Also used : ArrayList(java.util.ArrayList) ActivityManager(android.app.ActivityManager) RemoteException(android.os.RemoteException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ActivityNotFoundException(android.content.ActivityNotFoundException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) IApplicationThread(android.app.IApplicationThread) RemoteException(android.os.RemoteException)

Example 2 with IApplicationThread

use of android.app.IApplicationThread in project platform_frameworks_base by android.

the class ActivityManagerService method recordPssSampleLocked.

/**
     * Record new PSS sample for a process.
     */
void recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss, long now) {
    EventLogTags.writeAmPss(proc.pid, proc.uid, proc.processName, pss * 1024, uss * 1024, swapPss * 1024);
    proc.lastPssTime = now;
    proc.baseProcessTracker.addPss(pss, uss, true, proc.pkgList);
    if (DEBUG_PSS)
        Slog.d(TAG_PSS, "PSS of " + proc.toShortString() + ": " + pss + " lastPss=" + proc.lastPss + " state=" + ProcessList.makeProcStateString(procState));
    if (proc.initialIdlePss == 0) {
        proc.initialIdlePss = pss;
    }
    proc.lastPss = pss;
    proc.lastSwapPss = swapPss;
    if (procState >= ActivityManager.PROCESS_STATE_HOME) {
        proc.lastCachedPss = pss;
        proc.lastCachedSwapPss = swapPss;
    }
    final SparseArray<Pair<Long, String>> watchUids = mMemWatchProcesses.getMap().get(proc.processName);
    Long check = null;
    if (watchUids != null) {
        Pair<Long, String> val = watchUids.get(proc.uid);
        if (val == null) {
            val = watchUids.get(0);
        }
        if (val != null) {
            check = val.first;
        }
    }
    if (check != null) {
        if ((pss * 1024) >= check && proc.thread != null && mMemWatchDumpProcName == null) {
            boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
            if (!isDebuggable) {
                if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
                    isDebuggable = true;
                }
            }
            if (isDebuggable) {
                Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + "; reporting");
                final ProcessRecord myProc = proc;
                final File heapdumpFile = DumpHeapProvider.getJavaFile();
                mMemWatchDumpProcName = proc.processName;
                mMemWatchDumpFile = heapdumpFile.toString();
                mMemWatchDumpPid = proc.pid;
                mMemWatchDumpUid = proc.uid;
                BackgroundThread.getHandler().post(new Runnable() {

                    @Override
                    public void run() {
                        revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(), DumpHeapActivity.JAVA_URI, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION, UserHandle.myUserId());
                        ParcelFileDescriptor fd = null;
                        try {
                            heapdumpFile.delete();
                            fd = ParcelFileDescriptor.open(heapdumpFile, ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE | ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_APPEND);
                            IApplicationThread thread = myProc.thread;
                            if (thread != null) {
                                try {
                                    if (DEBUG_PSS)
                                        Slog.d(TAG_PSS, "Requesting dump heap from " + myProc + " to " + heapdumpFile);
                                    thread.dumpHeap(true, heapdumpFile.toString(), fd);
                                } catch (RemoteException e) {
                                }
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } finally {
                            if (fd != null) {
                                try {
                                    fd.close();
                                } catch (IOException e) {
                                }
                            }
                        }
                    }
                });
            } else {
                Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + ", but debugging not enabled");
            }
        }
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) IApplicationThread(android.app.IApplicationThread) AtomicLong(java.util.concurrent.atomic.AtomicLong) ParcelFileDescriptor(android.os.ParcelFileDescriptor) RemoteException(android.os.RemoteException) File(java.io.File) AtomicFile(android.util.AtomicFile) Pair(android.util.Pair)

Example 3 with IApplicationThread

use of android.app.IApplicationThread in project platform_frameworks_base by android.

the class ActivityManagerService method dumpApplicationMemoryUsage.

final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw) {
    boolean dumpDetails = false;
    boolean dumpFullDetails = false;
    boolean dumpDalvik = false;
    boolean dumpSummaryOnly = false;
    boolean dumpUnreachable = false;
    boolean oomOnly = false;
    boolean isCompact = false;
    boolean localOnly = false;
    boolean packages = false;
    boolean isCheckinRequest = false;
    boolean dumpSwapPss = false;
    int opti = 0;
    while (opti < args.length) {
        String opt = args[opti];
        if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
            break;
        }
        opti++;
        if ("-a".equals(opt)) {
            dumpDetails = true;
            dumpFullDetails = true;
            dumpDalvik = true;
            dumpSwapPss = true;
        } else if ("-d".equals(opt)) {
            dumpDalvik = true;
        } else if ("-c".equals(opt)) {
            isCompact = true;
        } else if ("-s".equals(opt)) {
            dumpDetails = true;
            dumpSummaryOnly = true;
        } else if ("-S".equals(opt)) {
            dumpSwapPss = true;
        } else if ("--unreachable".equals(opt)) {
            dumpUnreachable = true;
        } else if ("--oom".equals(opt)) {
            oomOnly = true;
        } else if ("--local".equals(opt)) {
            localOnly = true;
        } else if ("--package".equals(opt)) {
            packages = true;
        } else if ("--checkin".equals(opt)) {
            isCheckinRequest = true;
        } else if ("-h".equals(opt)) {
            pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]");
            pw.println("  -a: include all available information for each process.");
            pw.println("  -d: include dalvik details.");
            pw.println("  -c: dump in a compact machine-parseable representation.");
            pw.println("  -s: dump only summary of application memory usage.");
            pw.println("  -S: dump also SwapPss.");
            pw.println("  --oom: only show processes organized by oom adj.");
            pw.println("  --local: only collect details locally, don't call process.");
            pw.println("  --package: interpret process arg as package, dumping all");
            pw.println("             processes that have loaded that package.");
            pw.println("  --checkin: dump data for a checkin");
            pw.println("If [process] is specified it can be the name or ");
            pw.println("pid of a specific process to dump.");
            return;
        } else {
            pw.println("Unknown argument: " + opt + "; use -h for help");
        }
    }
    long uptime = SystemClock.uptimeMillis();
    long realtime = SystemClock.elapsedRealtime();
    final long[] tmpLong = new long[1];
    ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, packages, args);
    if (procs == null) {
        // No Java processes.  Maybe they want to print a native process.
        if (args != null && args.length > opti && args[opti].charAt(0) != '-') {
            ArrayList<ProcessCpuTracker.Stats> nativeProcs = new ArrayList<ProcessCpuTracker.Stats>();
            updateCpuStatsNow();
            int findPid = -1;
            try {
                findPid = Integer.parseInt(args[opti]);
            } catch (NumberFormatException e) {
            }
            synchronized (mProcessCpuTracker) {
                final int N = mProcessCpuTracker.countStats();
                for (int i = 0; i < N; i++) {
                    ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
                    if (st.pid == findPid || (st.baseName != null && st.baseName.equals(args[opti]))) {
                        nativeProcs.add(st);
                    }
                }
            }
            if (nativeProcs.size() > 0) {
                dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact);
                Debug.MemoryInfo mi = null;
                for (int i = nativeProcs.size() - 1; i >= 0; i--) {
                    final ProcessCpuTracker.Stats r = nativeProcs.get(i);
                    final int pid = r.pid;
                    if (!isCheckinRequest && dumpDetails) {
                        pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **");
                    }
                    if (mi == null) {
                        mi = new Debug.MemoryInfo();
                    }
                    if (dumpDetails || (!brief && !oomOnly)) {
                        Debug.getMemoryInfo(pid, mi);
                    } else {
                        mi.dalvikPss = (int) Debug.getPss(pid, tmpLong, null);
                        mi.dalvikPrivateDirty = (int) tmpLong[0];
                    }
                    ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, dumpDalvik, dumpSummaryOnly, pid, r.baseName, 0, 0, 0, 0, 0, 0);
                    if (isCheckinRequest) {
                        pw.println();
                    }
                }
                return;
            }
        }
        pw.println("No process found for: " + args[opti]);
        return;
    }
    if (!brief && !oomOnly && (procs.size() == 1 || isCheckinRequest || packages)) {
        dumpDetails = true;
    }
    dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact);
    String[] innerArgs = new String[args.length - opti];
    System.arraycopy(args, opti, innerArgs, 0, args.length - opti);
    ArrayList<MemItem> procMems = new ArrayList<MemItem>();
    final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
    long nativePss = 0;
    long nativeSwapPss = 0;
    long dalvikPss = 0;
    long dalvikSwapPss = 0;
    long[] dalvikSubitemPss = dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : EmptyArray.LONG;
    long[] dalvikSubitemSwapPss = dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : EmptyArray.LONG;
    long otherPss = 0;
    long otherSwapPss = 0;
    long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
    long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
    long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length];
    long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length];
    ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) new ArrayList[DUMP_MEM_OOM_LABEL.length];
    long totalPss = 0;
    long totalSwapPss = 0;
    long cachedPss = 0;
    long cachedSwapPss = 0;
    boolean hasSwapPss = false;
    Debug.MemoryInfo mi = null;
    for (int i = procs.size() - 1; i >= 0; i--) {
        final ProcessRecord r = procs.get(i);
        final IApplicationThread thread;
        final int pid;
        final int oomAdj;
        final boolean hasActivities;
        synchronized (this) {
            thread = r.thread;
            pid = r.pid;
            oomAdj = r.getSetAdjWithServices();
            hasActivities = r.activities.size() > 0;
        }
        if (thread != null) {
            if (!isCheckinRequest && dumpDetails) {
                pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
            }
            if (mi == null) {
                mi = new Debug.MemoryInfo();
            }
            if (dumpDetails || (!brief && !oomOnly)) {
                Debug.getMemoryInfo(pid, mi);
                hasSwapPss = mi.hasSwappedOutPss;
            } else {
                mi.dalvikPss = (int) Debug.getPss(pid, tmpLong, null);
                mi.dalvikPrivateDirty = (int) tmpLong[0];
            }
            if (dumpDetails) {
                if (localOnly) {
                    ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, dumpDalvik, dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0);
                    if (isCheckinRequest) {
                        pw.println();
                    }
                } else {
                    try {
                        pw.flush();
                        thread.dumpMemInfo(fd, mi, isCheckinRequest, dumpFullDetails, dumpDalvik, dumpSummaryOnly, dumpUnreachable, innerArgs);
                    } catch (RemoteException e) {
                        if (!isCheckinRequest) {
                            pw.println("Got RemoteException!");
                            pw.flush();
                        }
                    }
                }
            }
            final long myTotalPss = mi.getTotalPss();
            final long myTotalUss = mi.getTotalUss();
            final long myTotalSwapPss = mi.getTotalSwappedOutPss();
            synchronized (this) {
                if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
                    // Record this for posterity if the process has been stable.
                    r.baseProcessTracker.addPss(myTotalPss, myTotalUss, true, r.pkgList);
                }
            }
            if (!isCheckinRequest && mi != null) {
                totalPss += myTotalPss;
                totalSwapPss += myTotalSwapPss;
                MemItem pssItem = new MemItem(r.processName + " (pid " + pid + (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss, myTotalSwapPss, pid, hasActivities);
                procMems.add(pssItem);
                procMemsMap.put(pid, pssItem);
                nativePss += mi.nativePss;
                nativeSwapPss += mi.nativeSwappedOutPss;
                dalvikPss += mi.dalvikPss;
                dalvikSwapPss += mi.dalvikSwappedOutPss;
                for (int j = 0; j < dalvikSubitemPss.length; j++) {
                    dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
                    dalvikSubitemSwapPss[j] += mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
                }
                otherPss += mi.otherPss;
                otherSwapPss += mi.otherSwappedOutPss;
                for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
                    long mem = mi.getOtherPss(j);
                    miscPss[j] += mem;
                    otherPss -= mem;
                    mem = mi.getOtherSwappedOutPss(j);
                    miscSwapPss[j] += mem;
                    otherSwapPss -= mem;
                }
                if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
                    cachedPss += myTotalPss;
                    cachedSwapPss += myTotalSwapPss;
                }
                for (int oomIndex = 0; oomIndex < oomPss.length; oomIndex++) {
                    if (oomIndex == (oomPss.length - 1) || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex] && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
                        oomPss[oomIndex] += myTotalPss;
                        oomSwapPss[oomIndex] += myTotalSwapPss;
                        if (oomProcs[oomIndex] == null) {
                            oomProcs[oomIndex] = new ArrayList<MemItem>();
                        }
                        oomProcs[oomIndex].add(pssItem);
                        break;
                    }
                }
            }
        }
    }
    long nativeProcTotalPss = 0;
    if (!isCheckinRequest && procs.size() > 1 && !packages) {
        // If we are showing aggregations, also look for native processes to
        // include so that our aggregations are more accurate.
        updateCpuStatsNow();
        mi = null;
        synchronized (mProcessCpuTracker) {
            final int N = mProcessCpuTracker.countStats();
            for (int i = 0; i < N; i++) {
                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
                if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
                    if (mi == null) {
                        mi = new Debug.MemoryInfo();
                    }
                    if (!brief && !oomOnly) {
                        Debug.getMemoryInfo(st.pid, mi);
                    } else {
                        mi.nativePss = (int) Debug.getPss(st.pid, tmpLong, null);
                        mi.nativePrivateDirty = (int) tmpLong[0];
                    }
                    final long myTotalPss = mi.getTotalPss();
                    final long myTotalSwapPss = mi.getTotalSwappedOutPss();
                    totalPss += myTotalPss;
                    nativeProcTotalPss += myTotalPss;
                    MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", st.name, myTotalPss, mi.getSummaryTotalSwapPss(), st.pid, false);
                    procMems.add(pssItem);
                    nativePss += mi.nativePss;
                    nativeSwapPss += mi.nativeSwappedOutPss;
                    dalvikPss += mi.dalvikPss;
                    dalvikSwapPss += mi.dalvikSwappedOutPss;
                    for (int j = 0; j < dalvikSubitemPss.length; j++) {
                        dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
                        dalvikSubitemSwapPss[j] += mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
                    }
                    otherPss += mi.otherPss;
                    otherSwapPss += mi.otherSwappedOutPss;
                    for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
                        long mem = mi.getOtherPss(j);
                        miscPss[j] += mem;
                        otherPss -= mem;
                        mem = mi.getOtherSwappedOutPss(j);
                        miscSwapPss[j] += mem;
                        otherSwapPss -= mem;
                    }
                    oomPss[0] += myTotalPss;
                    oomSwapPss[0] += myTotalSwapPss;
                    if (oomProcs[0] == null) {
                        oomProcs[0] = new ArrayList<MemItem>();
                    }
                    oomProcs[0].add(pssItem);
                }
            }
        }
        ArrayList<MemItem> catMems = new ArrayList<MemItem>();
        catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, -1));
        final MemItem dalvikItem = new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, -2);
        if (dalvikSubitemPss.length > 0) {
            dalvikItem.subitems = new ArrayList<MemItem>();
            for (int j = 0; j < dalvikSubitemPss.length; j++) {
                final String name = Debug.MemoryInfo.getOtherLabel(Debug.MemoryInfo.NUM_OTHER_STATS + j);
                dalvikItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], dalvikSubitemSwapPss[j], j));
            }
        }
        catMems.add(dalvikItem);
        catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, -3));
        for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
            String label = Debug.MemoryInfo.getOtherLabel(j);
            catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], j));
        }
        ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
        for (int j = 0; j < oomPss.length; j++) {
            if (oomPss[j] != 0) {
                String label = isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] : DUMP_MEM_OOM_LABEL[j];
                MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], DUMP_MEM_OOM_ADJ[j]);
                item.subitems = oomProcs[j];
                oomMems.add(item);
            }
        }
        dumpSwapPss = dumpSwapPss && hasSwapPss && totalSwapPss != 0;
        if (!brief && !oomOnly && !isCompact) {
            pw.println();
            pw.println("Total PSS by process:");
            dumpMemItems(pw, "  ", "proc", procMems, true, isCompact, dumpSwapPss);
            pw.println();
        }
        if (!isCompact) {
            pw.println("Total PSS by OOM adjustment:");
        }
        dumpMemItems(pw, "  ", "oom", oomMems, false, isCompact, dumpSwapPss);
        if (!brief && !oomOnly) {
            PrintWriter out = categoryPw != null ? categoryPw : pw;
            if (!isCompact) {
                out.println();
                out.println("Total PSS by category:");
            }
            dumpMemItems(out, "  ", "cat", catMems, true, isCompact, dumpSwapPss);
        }
        if (!isCompact) {
            pw.println();
        }
        MemInfoReader memInfo = new MemInfoReader();
        memInfo.readMemInfo();
        if (nativeProcTotalPss > 0) {
            synchronized (this) {
                final long cachedKb = memInfo.getCachedSizeKb();
                final long freeKb = memInfo.getFreeSizeKb();
                final long zramKb = memInfo.getZramTotalSizeKb();
                final long kernelKb = memInfo.getKernelUsedSizeKb();
                EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024, kernelKb * 1024, nativeProcTotalPss * 1024);
                mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, nativeProcTotalPss);
            }
        }
        if (!brief) {
            if (!isCompact) {
                pw.print("Total RAM: ");
                pw.print(stringifyKBSize(memInfo.getTotalSizeKb()));
                pw.print(" (status ");
                switch(mLastMemoryLevel) {
                    case ProcessStats.ADJ_MEM_FACTOR_NORMAL:
                        pw.println("normal)");
                        break;
                    case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
                        pw.println("moderate)");
                        break;
                    case ProcessStats.ADJ_MEM_FACTOR_LOW:
                        pw.println("low)");
                        break;
                    case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
                        pw.println("critical)");
                        break;
                    default:
                        pw.print(mLastMemoryLevel);
                        pw.println(")");
                        break;
                }
                pw.print(" Free RAM: ");
                pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb() + memInfo.getFreeSizeKb()));
                pw.print(" (");
                pw.print(stringifyKBSize(cachedPss));
                pw.print(" cached pss + ");
                pw.print(stringifyKBSize(memInfo.getCachedSizeKb()));
                pw.print(" cached kernel + ");
                pw.print(stringifyKBSize(memInfo.getFreeSizeKb()));
                pw.println(" free)");
            } else {
                pw.print("ram,");
                pw.print(memInfo.getTotalSizeKb());
                pw.print(",");
                pw.print(cachedPss + memInfo.getCachedSizeKb() + memInfo.getFreeSizeKb());
                pw.print(",");
                pw.println(totalPss - cachedPss);
            }
        }
        long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss) - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
        if (!isCompact) {
            pw.print(" Used RAM: ");
            pw.print(stringifyKBSize(totalPss - cachedPss + memInfo.getKernelUsedSizeKb()));
            pw.print(" (");
            pw.print(stringifyKBSize(totalPss - cachedPss));
            pw.print(" used pss + ");
            pw.print(stringifyKBSize(memInfo.getKernelUsedSizeKb()));
            pw.print(" kernel)\n");
            pw.print(" Lost RAM: ");
            pw.println(stringifyKBSize(lostRAM));
        } else {
            pw.print("lostram,");
            pw.println(lostRAM);
        }
        if (!brief) {
            if (memInfo.getZramTotalSizeKb() != 0) {
                if (!isCompact) {
                    pw.print("     ZRAM: ");
                    pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb()));
                    pw.print(" physical used for ");
                    pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb()));
                    pw.print(" in swap (");
                    pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()));
                    pw.println(" total swap)");
                } else {
                    pw.print("zram,");
                    pw.print(memInfo.getZramTotalSizeKb());
                    pw.print(",");
                    pw.print(memInfo.getSwapTotalSizeKb());
                    pw.print(",");
                    pw.println(memInfo.getSwapFreeSizeKb());
                }
            }
            final long[] ksm = getKsmInfo();
            if (!isCompact) {
                if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 || ksm[KSM_VOLATILE] != 0) {
                    pw.print("      KSM: ");
                    pw.print(stringifyKBSize(ksm[KSM_SHARING]));
                    pw.print(" saved from shared ");
                    pw.print(stringifyKBSize(ksm[KSM_SHARED]));
                    pw.print("           ");
                    pw.print(stringifyKBSize(ksm[KSM_UNSHARED]));
                    pw.print(" unshared; ");
                    pw.print(stringifyKBSize(ksm[KSM_VOLATILE]));
                    pw.println(" volatile");
                }
                pw.print("   Tuning: ");
                pw.print(ActivityManager.staticGetMemoryClass());
                pw.print(" (large ");
                pw.print(ActivityManager.staticGetLargeMemoryClass());
                pw.print("), oom ");
                pw.print(stringifySize(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024));
                pw.print(", restore limit ");
                pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb()));
                if (ActivityManager.isLowRamDeviceStatic()) {
                    pw.print(" (low-ram)");
                }
                if (ActivityManager.isHighEndGfx()) {
                    pw.print(" (high-end-gfx)");
                }
                pw.println();
            } else {
                pw.print("ksm,");
                pw.print(ksm[KSM_SHARING]);
                pw.print(",");
                pw.print(ksm[KSM_SHARED]);
                pw.print(",");
                pw.print(ksm[KSM_UNSHARED]);
                pw.print(",");
                pw.println(ksm[KSM_VOLATILE]);
                pw.print("tuning,");
                pw.print(ActivityManager.staticGetMemoryClass());
                pw.print(',');
                pw.print(ActivityManager.staticGetLargeMemoryClass());
                pw.print(',');
                pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024);
                if (ActivityManager.isLowRamDeviceStatic()) {
                    pw.print(",low-ram");
                }
                if (ActivityManager.isHighEndGfx()) {
                    pw.print(",high-end-gfx");
                }
                pw.println();
            }
        }
    }
}
Also used : ProcessCpuTracker(com.android.internal.os.ProcessCpuTracker) ArrayList(java.util.ArrayList) MemInfoReader(com.android.internal.util.MemInfoReader) IApplicationThread(android.app.IApplicationThread) Debug(android.os.Debug) PrintWriter(java.io.PrintWriter) FastPrintWriter(com.android.internal.util.FastPrintWriter) Point(android.graphics.Point) SparseArray(android.util.SparseArray) BatteryStats(android.os.BatteryStats) ProcessStats(com.android.internal.app.procstats.ProcessStats) RemoteException(android.os.RemoteException)

Example 4 with IApplicationThread

use of android.app.IApplicationThread in project android_frameworks_base by ParanoidAndroid.

the class ActivityStack method activityIdleInternal.

final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout, Configuration config) {
    if (localLOGV)
        Slog.v(TAG, "Activity idle: " + token);
    ActivityRecord res = null;
    ArrayList<ActivityRecord> stops = null;
    ArrayList<ActivityRecord> finishes = null;
    ArrayList<ActivityRecord> thumbnails = null;
    ArrayList<UserStartedState> startingUsers = null;
    int NS = 0;
    int NF = 0;
    int NT = 0;
    IApplicationThread sendThumbnail = null;
    boolean booting = false;
    boolean enableScreen = false;
    boolean activityRemoved = false;
    synchronized (mService) {
        ActivityRecord r = ActivityRecord.forToken(token);
        if (r != null) {
            mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
            r.finishLaunchTickingLocked();
        }
        // Get the activity record.
        int index = indexOfActivityLocked(r);
        if (index >= 0) {
            res = r;
            if (fromTimeout) {
                reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
            }
            // it used to launch.
            if (config != null) {
                r.configuration = config;
            }
            // No longer need to keep the device awake.
            if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
                mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
                mLaunchingActivity.release();
            }
            // We are now idle.  If someone is waiting for a thumbnail from
            // us, we can now deliver.
            r.idle = true;
            mService.scheduleAppGcsLocked();
            if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
                sendThumbnail = r.app.thread;
                r.thumbnailNeeded = false;
            }
            if (DEBUG_VISBILITY)
                Slog.v(TAG, "Idle activity for " + r);
            ensureActivitiesVisibleLocked(null, 0);
            //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
            if (mMainStack) {
                if (!mService.mBooted) {
                    mService.mBooted = true;
                    enableScreen = true;
                }
            }
        } else if (fromTimeout) {
            reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
        }
        // Atomically retrieve all of the other things to do.
        stops = processStoppingActivitiesLocked(true);
        NS = stops != null ? stops.size() : 0;
        if ((NF = mFinishingActivities.size()) > 0) {
            finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
            mFinishingActivities.clear();
        }
        if ((NT = mService.mCancelledThumbnails.size()) > 0) {
            thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
            mService.mCancelledThumbnails.clear();
        }
        if (mMainStack) {
            booting = mService.mBooting;
            mService.mBooting = false;
        }
        if (mStartingUsers.size() > 0) {
            startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
            mStartingUsers.clear();
        }
    }
    int i;
    // Send thumbnail if requested.
    if (sendThumbnail != null) {
        try {
            sendThumbnail.requestThumbnail(token);
        } catch (Exception e) {
            Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
            mService.sendPendingThumbnail(null, token, null, null, true);
        }
    }
    // waiting for the next one to start.
    for (i = 0; i < NS; i++) {
        ActivityRecord r = (ActivityRecord) stops.get(i);
        synchronized (mService) {
            if (r.finishing) {
                finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
            } else {
                stopActivityLocked(r);
            }
        }
    }
    // waiting for the next one to start.
    for (i = 0; i < NF; i++) {
        ActivityRecord r = (ActivityRecord) finishes.get(i);
        synchronized (mService) {
            activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
        }
    }
    // Report back to any thumbnail receivers.
    for (i = 0; i < NT; i++) {
        ActivityRecord r = (ActivityRecord) thumbnails.get(i);
        mService.sendPendingThumbnail(r, null, null, null, true);
    }
    if (booting) {
        mService.finishBooting();
    } else if (startingUsers != null) {
        for (i = 0; i < startingUsers.size(); i++) {
            mService.finishUserSwitch(startingUsers.get(i));
        }
    }
    mService.trimApplications();
    if (enableScreen) {
        mService.enableScreenAfterBoot();
    }
    if (activityRemoved) {
        synchronized (mService) {
            resumeTopActivityLocked(null);
        }
    }
    return res;
}
Also used : IApplicationThread(android.app.IApplicationThread) RemoteException(android.os.RemoteException) IOException(java.io.IOException)

Example 5 with IApplicationThread

use of android.app.IApplicationThread in project cornerstone by Onskreen.

the class ActivityManagerService method getTasks.

// =========================================================
// TASK MANAGEMENT
// =========================================================
/**
     * Author: Onskreen
     * Date: 27/01/2011
     *
     * Does not include cornerstone tasks. This shouldn't create a functional issue?
     */
public List getTasks(int maxNum, int flags, IThumbnailReceiver receiver) {
    ArrayList list = new ArrayList();
    PendingThumbnailsRecord pending = null;
    IApplicationThread topThumbnail = null;
    ActivityRecord topRecord = null;
    synchronized (this) {
        if (localLOGV)
            Slog.v(TAG, "getTasks: max=" + maxNum + ", flags=" + flags + ", receiver=" + receiver);
        if (checkCallingPermission(android.Manifest.permission.GET_TASKS) != PackageManager.PERMISSION_GRANTED) {
            if (receiver != null) {
                // it ain't gonna get them.
                try {
                    receiver.finished();
                } catch (RemoteException ex) {
                }
            }
            String msg = "Permission Denial: getTasks() from pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() + " requires " + android.Manifest.permission.GET_TASKS;
            Slog.w(TAG, msg);
            throw new SecurityException(msg);
        }
        int pos = mMainStack.mHistory.size() - 1;
        ActivityRecord next = pos >= 0 ? (ActivityRecord) mMainStack.mHistory.get(pos) : null;
        ActivityRecord top = null;
        TaskRecord curTask = null;
        int numActivities = 0;
        int numRunning = 0;
        while (pos >= 0 && maxNum > 0) {
            final ActivityRecord r = next;
            pos--;
            next = pos >= 0 ? (ActivityRecord) mMainStack.mHistory.get(pos) : null;
            // Initialize state for next task if needed.
            if (top == null || (top.state == ActivityState.INITIALIZING && top.task == r.task)) {
                top = r;
                curTask = r.task;
                numActivities = numRunning = 0;
            }
            // Add 'r' into the current task.
            numActivities++;
            if (r.app != null && r.app.thread != null) {
                numRunning++;
            }
            if (localLOGV)
                Slog.v(TAG, r.intent.getComponent().flattenToShortString() + ": task=" + r.task);
            // TaskInfo entry for what we have.
            if (next == null || next.task != curTask) {
                ActivityManager.RunningTaskInfo ci = new ActivityManager.RunningTaskInfo();
                ci.id = curTask.taskId;
                ci.baseActivity = r.intent.getComponent();
                ci.topActivity = top.intent.getComponent();
                if (top.thumbHolder != null) {
                    ci.description = top.thumbHolder.lastDescription;
                }
                ci.numActivities = numActivities;
                ci.numRunning = numRunning;
                //    "#" + maxNum + ": " + " descr=" + ci.description);
                if (ci.thumbnail == null && receiver != null) {
                    if (localLOGV)
                        Slog.v(TAG, "State=" + top.state + "Idle=" + top.idle + " app=" + top.app + " thr=" + (top.app != null ? top.app.thread : null));
                    if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
                        if (top.idle && top.app != null && top.app.thread != null) {
                            topRecord = top;
                            topThumbnail = top.app.thread;
                        } else {
                            top.thumbnailNeeded = true;
                        }
                    }
                    if (pending == null) {
                        pending = new PendingThumbnailsRecord(receiver);
                    }
                    pending.pendingRecords.add(top);
                }
                list.add(ci);
                maxNum--;
                top = null;
            }
        }
        if (pending != null) {
            mPendingThumbnails.add(pending);
        }
    }
    if (localLOGV)
        Slog.v(TAG, "We have pending thumbnails: " + pending);
    if (topThumbnail != null) {
        if (localLOGV)
            Slog.v(TAG, "Requesting top thumbnail");
        try {
            topThumbnail.requestThumbnail(topRecord.appToken);
        } catch (Exception e) {
            Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
            sendPendingThumbnail(null, topRecord.appToken, null, null, true);
        }
    }
    if (pending == null && receiver != null) {
        // activity should never have a canned thumbnail!  Oh well.
        try {
            receiver.finished();
        } catch (RemoteException ex) {
        }
    }
    return list;
}
Also used : ArrayList(java.util.ArrayList) ActivityManager(android.app.ActivityManager) RemoteException(android.os.RemoteException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) ActivityNotFoundException(android.content.ActivityNotFoundException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) IApplicationThread(android.app.IApplicationThread) RemoteException(android.os.RemoteException)

Aggregations

IApplicationThread (android.app.IApplicationThread)8 RemoteException (android.os.RemoteException)8 IOException (java.io.IOException)6 FileNotFoundException (java.io.FileNotFoundException)4 ArrayList (java.util.ArrayList)4 ActivityManager (android.app.ActivityManager)2 ActivityNotFoundException (android.content.ActivityNotFoundException)2 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)2 Point (android.graphics.Point)2 BatteryStats (android.os.BatteryStats)2 Debug (android.os.Debug)2 ParcelFileDescriptor (android.os.ParcelFileDescriptor)2 AtomicFile (android.util.AtomicFile)2 Pair (android.util.Pair)2 SparseArray (android.util.SparseArray)2 ProcessStats (com.android.internal.app.procstats.ProcessStats)2 ProcessCpuTracker (com.android.internal.os.ProcessCpuTracker)2 FastPrintWriter (com.android.internal.util.FastPrintWriter)2 MemInfoReader (com.android.internal.util.MemInfoReader)2 File (java.io.File)2