Merge "Bug fixes of DRM framework."
diff --git a/drm/common/DrmSupportInfo.cpp b/drm/common/DrmSupportInfo.cpp
index 3e02093..c0bff0e 100644
--- a/drm/common/DrmSupportInfo.cpp
+++ b/drm/common/DrmSupportInfo.cpp
@@ -45,7 +45,7 @@
     for (unsigned int i = 0; i < mMimeTypeVector.size(); i++) {
         const String8 item = mMimeTypeVector.itemAt(i);
 
-        if (String8("") != mimeType && item.find(mimeType) != -1) {
+        if (!strcasecmp(item.string(), mimeType.string())) {
             return true;
         }
     }
@@ -56,7 +56,7 @@
     for (unsigned int i = 0; i < mFileSuffixVector.size(); i++) {
         const String8 item = mFileSuffixVector.itemAt(i);
 
-        if (item.find(fileType) != -1) {
+        if (!strcasecmp(item.string(), fileType.string())) {
             return true;
         }
     }
diff --git a/drm/drmserver/Android.mk b/drm/drmserver/Android.mk
index 5df2ff8..e3cd44f 100644
--- a/drm/drmserver/Android.mk
+++ b/drm/drmserver/Android.mk
@@ -19,10 +19,10 @@
 LOCAL_SRC_FILES:= \
     main_drmserver.cpp \
     DrmManager.cpp \
-    DrmManagerService.cpp \
-    StringTokenizer.cpp
+    DrmManagerService.cpp
 
 LOCAL_SHARED_LIBRARIES := \
+    libmedia \
     libutils \
     libbinder
 
diff --git a/drm/drmserver/DrmManager.cpp b/drm/drmserver/DrmManager.cpp
index f44c06d..2fee59c 100644
--- a/drm/drmserver/DrmManager.cpp
+++ b/drm/drmserver/DrmManager.cpp
@@ -118,7 +118,7 @@
 
 status_t DrmManager::setDrmServiceListener(
             int uniqueId, const sp<IDrmServiceListener>& drmServiceListener) {
-    Mutex::Autolock _l(mLock);
+    Mutex::Autolock _l(mListenerLock);
     if (NULL != drmServiceListener.get()) {
         mServiceListeners.add(uniqueId, drmServiceListener);
     } else {
@@ -572,7 +572,7 @@
 }
 
 void DrmManager::onInfo(const DrmInfoEvent& event) {
-    Mutex::Autolock _l(mLock);
+    Mutex::Autolock _l(mListenerLock);
     for (unsigned int index = 0; index < mServiceListeners.size(); index++) {
         int uniqueId = mServiceListeners.keyAt(index);
 
diff --git a/drm/drmserver/DrmManagerService.cpp b/drm/drmserver/DrmManagerService.cpp
index 0901a44..583669e 100644
--- a/drm/drmserver/DrmManagerService.cpp
+++ b/drm/drmserver/DrmManagerService.cpp
@@ -19,6 +19,7 @@
 #include <utils/Log.h>
 
 #include <private/android_filesystem_config.h>
+#include <media/MemoryLeakTrackUtil.h>
 
 #include <errno.h>
 #include <utils/threads.h>
@@ -256,3 +257,31 @@
     return mDrmManager->pread(uniqueId, decryptHandle, buffer, numBytes, offset);
 }
 
+status_t DrmManagerService::dump(int fd, const Vector<String16>& args)
+{
+    const size_t SIZE = 256;
+    char buffer[SIZE];
+    String8 result;
+    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
+        snprintf(buffer, SIZE, "Permission Denial: "
+                "can't dump DrmManagerService from pid=%d, uid=%d\n",
+                IPCThreadState::self()->getCallingPid(),
+                IPCThreadState::self()->getCallingUid());
+        result.append(buffer);
+    } else {
+#if DRM_MEMORY_LEAK_TRACK
+        bool dumpMem = false;
+        for (size_t i = 0; i < args.size(); i++) {
+            if (args[i] == String16("-m")) {
+                dumpMem = true;
+            }
+        }
+        if (dumpMem) {
+            dumpMemoryAddresses(fd);
+        }
+#endif
+    }
+    write(fd, result.string(), result.size());
+    return NO_ERROR;
+}
+
diff --git a/drm/drmserver/StringTokenizer.cpp b/drm/drmserver/StringTokenizer.cpp
deleted file mode 100644
index 2130a00..0000000
--- a/drm/drmserver/StringTokenizer.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "StringTokenizer.h"
-
-using namespace android;
-
-StringTokenizer::StringTokenizer(const String8& string, const String8& delimiter) {
-    splitString(string, delimiter);
-}
-
-void StringTokenizer::splitString(const String8& string, const String8& delimiter) {
-    for (unsigned int i = 0; i < string.length(); i++) {
-        unsigned int position = string.find(delimiter.string(), i);
-        if (string.length() != position) {
-            String8 token(string.string()+i, position-i);
-            if (token.length()) {
-                mStringTokenizerVector.push(token);
-                i = position + delimiter.length() - 1;
-            }
-        } else {
-            mStringTokenizerVector.push(String8(string.string()+i, string.length()-i));
-            break;
-        }
-    }
-}
-
-StringTokenizer::Iterator StringTokenizer::iterator() {
-    return Iterator(this);
-}
-
-StringTokenizer::Iterator::Iterator(const StringTokenizer::Iterator& iterator) :
-    mStringTokenizer(iterator.mStringTokenizer),
-    mIndex(iterator.mIndex) {
-}
-
-StringTokenizer::Iterator& StringTokenizer::Iterator::operator=(
-            const StringTokenizer::Iterator& iterator) {
-    mStringTokenizer = iterator.mStringTokenizer;
-    mIndex = iterator.mIndex;
-    return *this;
-}
-
-bool StringTokenizer::Iterator::hasNext() {
-    return mIndex < mStringTokenizer->mStringTokenizerVector.size();
-}
-
-String8& StringTokenizer::Iterator::next() {
-    String8& value = mStringTokenizer->mStringTokenizerVector.editItemAt(mIndex);
-    mIndex++;
-    return value;
-}
-
diff --git a/drm/libdrmframework/Android.mk b/drm/libdrmframework/Android.mk
index 99133ba..f1526a4 100644
--- a/drm/libdrmframework/Android.mk
+++ b/drm/libdrmframework/Android.mk
@@ -40,7 +40,7 @@
     $(TOP)/frameworks/base/drm/libdrmframework/include \
     $(TOP)/frameworks/base/include
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_MODULE_TAGS := optional
 
diff --git a/drm/libdrmframework/DrmManagerClient.cpp b/drm/libdrmframework/DrmManagerClient.cpp
index 3143d45..8b78132 100644
--- a/drm/libdrmframework/DrmManagerClient.cpp
+++ b/drm/libdrmframework/DrmManagerClient.cpp
@@ -79,7 +79,6 @@
 
 status_t DrmManagerClient::consumeRights(
             sp<DecryptHandle> &decryptHandle, int action, bool reserve) {
-    Mutex::Autolock _l(mDecryptLock);
     return mDrmManagerClientImpl->consumeRights(mUniqueId, decryptHandle, action, reserve);
 }
 
@@ -132,7 +131,6 @@
 
 status_t DrmManagerClient::initializeDecryptUnit(
             sp<DecryptHandle> &decryptHandle, int decryptUnitId, const DrmBuffer* headerInfo) {
-    Mutex::Autolock _l(mDecryptLock);
     return mDrmManagerClientImpl->initializeDecryptUnit(
             mUniqueId, decryptHandle, decryptUnitId, headerInfo);
 }
@@ -140,21 +138,18 @@
 status_t DrmManagerClient::decrypt(
             sp<DecryptHandle> &decryptHandle, int decryptUnitId,
             const DrmBuffer* encBuffer, DrmBuffer** decBuffer, DrmBuffer* IV) {
-    Mutex::Autolock _l(mDecryptLock);
     return mDrmManagerClientImpl->decrypt(
             mUniqueId, decryptHandle, decryptUnitId, encBuffer, decBuffer, IV);
 }
 
 status_t DrmManagerClient::finalizeDecryptUnit(
             sp<DecryptHandle> &decryptHandle, int decryptUnitId) {
-    Mutex::Autolock _l(mDecryptLock);
     return mDrmManagerClientImpl->finalizeDecryptUnit(mUniqueId,
             decryptHandle, decryptUnitId);
 }
 
 ssize_t DrmManagerClient::pread(
             sp<DecryptHandle> &decryptHandle, void* buffer, ssize_t numBytes, off64_t offset) {
-    Mutex::Autolock _l(mDecryptLock);
     return mDrmManagerClientImpl->pread(mUniqueId, decryptHandle, buffer, numBytes, offset);
 }
 
diff --git a/drm/libdrmframework/include/DrmManager.h b/drm/libdrmframework/include/DrmManager.h
index 86a5ff4..af2c2a8 100644
--- a/drm/libdrmframework/include/DrmManager.h
+++ b/drm/libdrmframework/include/DrmManager.h
@@ -146,6 +146,7 @@
     int mDecryptSessionId;
     int mConvertId;
     Mutex mLock;
+    Mutex mListenerLock;
     Mutex mDecryptLock;
     Mutex mConvertLock;
     TPlugInManager<IDrmEngine> mPlugInManager;
diff --git a/drm/libdrmframework/include/DrmManagerService.h b/drm/libdrmframework/include/DrmManagerService.h
index d0a0db7..227496a 100644
--- a/drm/libdrmframework/include/DrmManagerService.h
+++ b/drm/libdrmframework/include/DrmManagerService.h
@@ -115,6 +115,8 @@
     ssize_t pread(int uniqueId, DecryptHandle* decryptHandle,
             void* buffer, ssize_t numBytes, off64_t offset);
 
+    virtual status_t dump(int fd, const Vector<String16>& args);
+
 private:
     DrmManager* mDrmManager;
 };
diff --git a/drm/libdrmframework/include/PlugInManager.h b/drm/libdrmframework/include/PlugInManager.h
index 9ad195f..8029138 100644
--- a/drm/libdrmframework/include/PlugInManager.h
+++ b/drm/libdrmframework/include/PlugInManager.h
@@ -230,11 +230,9 @@
      */
     bool isPlugIn(const struct dirent* pEntry) const {
         String8 sName(pEntry->d_name);
-        int extentionPos = sName.size() - String8(PLUGIN_EXTENSION).size();
-        if (extentionPos < 0) {
-            return false;
-        }
-        return extentionPos == (int)sName.find(PLUGIN_EXTENSION);
+        String8 extension(sName.getPathExtension());
+        // Note that the plug-in extension must exactly match case
+        return extension == String8(PLUGIN_EXTENSION);
     }
 
     /**
diff --git a/drm/libdrmframework/include/StringTokenizer.h b/drm/libdrmframework/include/StringTokenizer.h
deleted file mode 100644
index 70e7558..0000000
--- a/drm/libdrmframework/include/StringTokenizer.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __STRING_TOKENIZER_H__
-#define __STRING_TOKENIZER_H__
-
-#include <drm/drm_framework_common.h>
-
-namespace android {
-
-/**
- * This is an utility class for String manipulation.
- *
- */
-class StringTokenizer {
-public:
-    /**
-     * Iterator for string tokens
-     */
-    class Iterator {
-        friend class StringTokenizer;
-    private:
-        Iterator(StringTokenizer* StringTokenizer)
-         : mStringTokenizer(StringTokenizer), mIndex(0) {}
-
-    public:
-        Iterator(const Iterator& iterator);
-        Iterator& operator=(const Iterator& iterator);
-        virtual ~Iterator() {}
-
-    public:
-        bool hasNext();
-        String8& next();
-
-    private:
-        StringTokenizer* mStringTokenizer;
-        unsigned int mIndex;
-    };
-
-public:
-    /**
-     * Constructor for StringTokenizer
-     *
-     * @param[in] string Complete string data
-     * @param[in] delimeter Delimeter used to split the string
-     */
-    StringTokenizer(const String8& string, const String8& delimeter);
-
-    /**
-     * Destructor for StringTokenizer
-     */
-    ~StringTokenizer() {}
-
-private:
-    /**
-     * Splits the string according to the delimeter
-     */
-    void splitString(const String8& string, const String8& delimeter);
-
-public:
-    /**
-     * Returns Iterator object to walk through the split string values
-     *
-     * @return Iterator object
-     */
-    Iterator iterator();
-
-private:
-    Vector<String8> mStringTokenizerVector;
-};
-
-};
-#endif /* __STRING_TOKENIZER_H__ */
-
diff --git a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.mk b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.mk
index af67aa3..9805a40 100644
--- a/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.mk
+++ b/drm/libdrmframework/plugins/forward-lock/FwdLockEngine/Android.mk
@@ -47,7 +47,7 @@
     libfwdlock-converter \
     libfwdlock-decoder
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_C_INCLUDES += \
     $(JNI_H_INCLUDE) \
diff --git a/drm/libdrmframework/plugins/passthru/Android.mk b/drm/libdrmframework/plugins/passthru/Android.mk
index 7856d37..be18b64 100644
--- a/drm/libdrmframework/plugins/passthru/Android.mk
+++ b/drm/libdrmframework/plugins/passthru/Android.mk
@@ -32,7 +32,7 @@
  LOCAL_SHARED_LIBRARIES += libdl
 endif
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_C_INCLUDES += \
     $(TOP)/frameworks/base/drm/libdrmframework/include \
diff --git a/include/drm/DrmInfoEvent.h b/include/drm/DrmInfoEvent.h
index 7b409ff..add33d3 100644
--- a/include/drm/DrmInfoEvent.h
+++ b/include/drm/DrmInfoEvent.h
@@ -43,6 +43,8 @@
     //! TYPE_ACCOUNT_ALREADY_REGISTERED, when registration has been
     //! already done for the given account.
     static const int TYPE_ACCOUNT_ALREADY_REGISTERED = 5;
+    //! TYPE_RIGHTS_REMOVED, when the rights has been removed.
+    static const int TYPE_RIGHTS_REMOVED = 6;
 
     /**
      * The following constant values should be in sync with DrmErrorEvent.java
@@ -61,6 +63,11 @@
     static const int TYPE_NO_INTERNET_CONNECTION = 2005;
     //! TYPE_PROCESS_DRM_INFO_FAILED, when failed to process DrmInfo.
     static const int TYPE_PROCESS_DRM_INFO_FAILED = 2006;
+    //! TYPE_REMOVE_ALL_RIGHTS_FAILED, when failed to remove all the rights objects
+    //! associated with all DRM schemes.
+    static const int TYPE_REMOVE_ALL_RIGHTS_FAILED = 2007;
+    //! TYPE_ACQUIRE_DRM_INFO_FAILED, when failed to acquire DrmInfo.
+    static const int TYPE_ACQUIRE_DRM_INFO_FAILED = 2008;
 
 public:
     /**
diff --git a/include/drm/DrmManagerClient.h b/include/drm/DrmManagerClient.h
index 044ff0e..5011137 100644
--- a/include/drm/DrmManagerClient.h
+++ b/include/drm/DrmManagerClient.h
@@ -368,7 +368,6 @@
 
 private:
     int mUniqueId;
-    Mutex mDecryptLock;
     DrmManagerClientImpl* mDrmManagerClientImpl;
 };
 
diff --git a/include/media/MemoryLeakTrackUtil.h b/include/media/MemoryLeakTrackUtil.h
new file mode 100644
index 0000000..290b748
--- /dev/null
+++ b/include/media/MemoryLeakTrackUtil.h
@@ -0,0 +1,28 @@
+
+/*
+ * Copyright 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#ifndef MEMORY_LEAK_TRACK_UTIL_H
+#define MEMORY_LEAK_TRACK_UTIL_H
+
+namespace android {
+/*
+ * Dump the memory adddress of the calling process to the given fd.
+ */
+extern void dumpMemoryAddresses(int fd);
+
+};
+
+#endif  // MEMORY_LEAK_TRACK_UTIL_H
diff --git a/media/libeffects/lvm/lib/Android.mk b/media/libeffects/lvm/lib/Android.mk
index ff34707..f49267e 100644
--- a/media/libeffects/lvm/lib/Android.mk
+++ b/media/libeffects/lvm/lib/Android.mk
@@ -105,7 +105,7 @@
 
 LOCAL_MODULE:= libmusicbundle
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_C_INCLUDES += \
     $(LOCAL_PATH)/Eq/lib \
@@ -168,7 +168,7 @@
 
 LOCAL_MODULE:= libreverb
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_C_INCLUDES += \
     $(LOCAL_PATH)/Reverb/lib \
diff --git a/media/libeffects/lvm/wrapper/Android.mk b/media/libeffects/lvm/wrapper/Android.mk
index 2e9b9b4..99cfdfa 100644
--- a/media/libeffects/lvm/wrapper/Android.mk
+++ b/media/libeffects/lvm/wrapper/Android.mk
@@ -13,7 +13,7 @@
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/soundfx
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_STATIC_LIBRARIES += libmusicbundle
 
@@ -47,7 +47,7 @@
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/soundfx
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_STATIC_LIBRARIES += libreverb
 
diff --git a/media/libeffects/visualizer/Android.mk b/media/libeffects/visualizer/Android.mk
index e6ff654..3a0f438 100644
--- a/media/libeffects/visualizer/Android.mk
+++ b/media/libeffects/visualizer/Android.mk
@@ -25,6 +25,6 @@
 LOCAL_C_INCLUDES := \
 	$(call include-path-for, graphics corecg)
 
-LOCAL_PRELINK_MODULE := false
+
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index fd4c6c6..a04fbd2 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -33,6 +33,7 @@
     IEffectClient.cpp \
     AudioEffect.cpp \
     Visualizer.cpp \
+    MemoryLeakTrackUtil.cpp \
     fixedfft.cpp.arm
 
 LOCAL_SHARED_LIBRARIES := \
diff --git a/media/libmedia/MemoryLeakTrackUtil.cpp b/media/libmedia/MemoryLeakTrackUtil.cpp
new file mode 100644
index 0000000..6a108ae
--- /dev/null
+++ b/media/libmedia/MemoryLeakTrackUtil.cpp
@@ -0,0 +1,169 @@
+/*
+ * Copyright 2011, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <media/MemoryLeakTrackUtil.h>
+
+#include <stdio.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+/*
+ * The code here originally resided in MediaPlayerService.cpp and was
+ * shamelessly copied over to support memory leak tracking from
+ * multiple places.
+ */
+namespace android {
+
+#if defined(__arm__)
+
+extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
+        size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
+
+extern "C" void free_malloc_leak_info(uint8_t* info);
+
+// Use the String-class below instead of String8 to allocate all memory
+// beforehand and not reenter the heap while we are examining it...
+struct MyString8 {
+    static const size_t MAX_SIZE = 256 * 1024;
+
+    MyString8()
+        : mPtr((char *)malloc(MAX_SIZE)) {
+        *mPtr = '\0';
+    }
+
+    ~MyString8() {
+        free(mPtr);
+    }
+
+    void append(const char *s) {
+        strcat(mPtr, s);
+    }
+
+    const char *string() const {
+        return mPtr;
+    }
+
+    size_t size() const {
+        return strlen(mPtr);
+    }
+
+private:
+    char *mPtr;
+
+    MyString8(const MyString8 &);
+    MyString8 &operator=(const MyString8 &);
+};
+
+void dumpMemoryAddresses(int fd)
+{
+    const size_t SIZE = 256;
+    char buffer[SIZE];
+    MyString8 result;
+
+    typedef struct {
+        size_t size;
+        size_t dups;
+        intptr_t * backtrace;
+    } AllocEntry;
+
+    uint8_t *info = NULL;
+    size_t overallSize = 0;
+    size_t infoSize = 0;
+    size_t totalMemory = 0;
+    size_t backtraceSize = 0;
+
+    get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
+    if (info) {
+        uint8_t *ptr = info;
+        size_t count = overallSize / infoSize;
+
+        snprintf(buffer, SIZE, " Allocation count %i\n", count);
+        result.append(buffer);
+        snprintf(buffer, SIZE, " Total memory %i\n", totalMemory);
+        result.append(buffer);
+
+        AllocEntry * entries = new AllocEntry[count];
+
+        for (size_t i = 0; i < count; i++) {
+            // Each entry should be size_t, size_t, intptr_t[backtraceSize]
+            AllocEntry *e = &entries[i];
+
+            e->size = *reinterpret_cast<size_t *>(ptr);
+            ptr += sizeof(size_t);
+
+            e->dups = *reinterpret_cast<size_t *>(ptr);
+            ptr += sizeof(size_t);
+
+            e->backtrace = reinterpret_cast<intptr_t *>(ptr);
+            ptr += sizeof(intptr_t) * backtraceSize;
+        }
+
+        // Now we need to sort the entries.  They come sorted by size but
+        // not by stack trace which causes problems using diff.
+        bool moved;
+        do {
+            moved = false;
+            for (size_t i = 0; i < (count - 1); i++) {
+                AllocEntry *e1 = &entries[i];
+                AllocEntry *e2 = &entries[i+1];
+
+                bool swap = e1->size < e2->size;
+                if (e1->size == e2->size) {
+                    for(size_t j = 0; j < backtraceSize; j++) {
+                        if (e1->backtrace[j] == e2->backtrace[j]) {
+                            continue;
+                        }
+                        swap = e1->backtrace[j] < e2->backtrace[j];
+                        break;
+                    }
+                }
+                if (swap) {
+                    AllocEntry t = entries[i];
+                    entries[i] = entries[i+1];
+                    entries[i+1] = t;
+                    moved = true;
+                }
+            }
+        } while (moved);
+
+        for (size_t i = 0; i < count; i++) {
+            AllocEntry *e = &entries[i];
+
+            snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups);
+            result.append(buffer);
+            for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
+                if (ct) {
+                    result.append(", ");
+                }
+                snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
+                result.append(buffer);
+            }
+            result.append("\n");
+        }
+
+        delete[] entries;
+        free_malloc_leak_info(info);
+    }
+
+    write(fd, result.string(), result.size());
+}
+
+#else
+// Does nothing
+void dumpMemoryAddresses(int fd) {}
+
+#endif
+}  // namespace android
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index a42cca5..f075706 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -51,6 +51,7 @@
 #include <media/MediaMetadataRetrieverInterface.h>
 #include <media/Metadata.h>
 #include <media/AudioTrack.h>
+#include <media/MemoryLeakTrackUtil.h>
 
 #include <private/android_filesystem_config.h>
 
@@ -392,139 +393,6 @@
 #endif
 }
 
-#if defined(__arm__)
-extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
-        size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
-extern "C" void free_malloc_leak_info(uint8_t* info);
-
-// Use the String-class below instead of String8 to allocate all memory
-// beforehand and not reenter the heap while we are examining it...
-struct MyString8 {
-    static const size_t MAX_SIZE = 256 * 1024;
-
-    MyString8()
-        : mPtr((char *)malloc(MAX_SIZE)) {
-        *mPtr = '\0';
-    }
-
-    ~MyString8() {
-        free(mPtr);
-    }
-
-    void append(const char *s) {
-        strcat(mPtr, s);
-    }
-
-    const char *string() const {
-        return mPtr;
-    }
-
-    size_t size() const {
-        return strlen(mPtr);
-    }
-
-private:
-    char *mPtr;
-
-    MyString8(const MyString8 &);
-    MyString8 &operator=(const MyString8 &);
-};
-
-void memStatus(int fd, const Vector<String16>& args)
-{
-    const size_t SIZE = 256;
-    char buffer[SIZE];
-    MyString8 result;
-
-    typedef struct {
-        size_t size;
-        size_t dups;
-        intptr_t * backtrace;
-    } AllocEntry;
-
-    uint8_t *info = NULL;
-    size_t overallSize = 0;
-    size_t infoSize = 0;
-    size_t totalMemory = 0;
-    size_t backtraceSize = 0;
-
-    get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory, &backtraceSize);
-    if (info) {
-        uint8_t *ptr = info;
-        size_t count = overallSize / infoSize;
-
-        snprintf(buffer, SIZE, " Allocation count %i\n", count);
-        result.append(buffer);
-        snprintf(buffer, SIZE, " Total memory %i\n", totalMemory);
-        result.append(buffer);
-
-        AllocEntry * entries = new AllocEntry[count];
-
-        for (size_t i = 0; i < count; i++) {
-            // Each entry should be size_t, size_t, intptr_t[backtraceSize]
-            AllocEntry *e = &entries[i];
-
-            e->size = *reinterpret_cast<size_t *>(ptr);
-            ptr += sizeof(size_t);
-
-            e->dups = *reinterpret_cast<size_t *>(ptr);
-            ptr += sizeof(size_t);
-
-            e->backtrace = reinterpret_cast<intptr_t *>(ptr);
-            ptr += sizeof(intptr_t) * backtraceSize;
-        }
-
-        // Now we need to sort the entries.  They come sorted by size but
-        // not by stack trace which causes problems using diff.
-        bool moved;
-        do {
-            moved = false;
-            for (size_t i = 0; i < (count - 1); i++) {
-                AllocEntry *e1 = &entries[i];
-                AllocEntry *e2 = &entries[i+1];
-
-                bool swap = e1->size < e2->size;
-                if (e1->size == e2->size) {
-                    for(size_t j = 0; j < backtraceSize; j++) {
-                        if (e1->backtrace[j] == e2->backtrace[j]) {
-                            continue;
-                        }
-                        swap = e1->backtrace[j] < e2->backtrace[j];
-                        break;
-                    }
-                }
-                if (swap) {
-                    AllocEntry t = entries[i];
-                    entries[i] = entries[i+1];
-                    entries[i+1] = t;
-                    moved = true;
-                }
-            }
-        } while (moved);
-
-        for (size_t i = 0; i < count; i++) {
-            AllocEntry *e = &entries[i];
-
-            snprintf(buffer, SIZE, "size %8i, dup %4i, ", e->size, e->dups);
-            result.append(buffer);
-            for (size_t ct = 0; (ct < backtraceSize) && e->backtrace[ct]; ct++) {
-                if (ct) {
-                    result.append(", ");
-                }
-                snprintf(buffer, SIZE, "0x%08x", e->backtrace[ct]);
-                result.append(buffer);
-            }
-            result.append("\n");
-        }
-
-        delete[] entries;
-        free_malloc_leak_info(info);
-    }
-
-    write(fd, result.string(), result.size());
-}
-#endif
-
 status_t MediaPlayerService::dump(int fd, const Vector<String16>& args)
 {
     const size_t SIZE = 256;
@@ -623,7 +491,6 @@
             result.append("\n");
         }
 
-#if defined(__arm__)
         bool dumpMem = false;
         for (size_t i = 0; i < args.size(); i++) {
             if (args[i] == String16("-m")) {
@@ -631,9 +498,8 @@
             }
         }
         if (dumpMem) {
-            memStatus(fd, args);
+            dumpMemoryAddresses(fd);
         }
-#endif
     }
     write(fd, result.string(), result.size());
     return NO_ERROR;
diff --git a/media/libstagefright/WAVExtractor.cpp b/media/libstagefright/WAVExtractor.cpp
index 9332120..e9e5ef9 100644
--- a/media/libstagefright/WAVExtractor.cpp
+++ b/media/libstagefright/WAVExtractor.cpp
@@ -353,8 +353,6 @@
         return ERROR_END_OF_STREAM;
     }
 
-    mCurrentPos += n;
-
     buffer->set_range(0, n);
 
     if (mWaveFormat == WAVE_FORMAT_PCM) {
@@ -406,6 +404,7 @@
                 / (mNumChannels * bytesPerSample) / mSampleRate);
 
     buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
+    mCurrentPos += n;
 
     *out = buffer;
 
diff --git a/media/libstagefright/codecs/aacdec/sbr_dec.cpp b/media/libstagefright/codecs/aacdec/sbr_dec.cpp
index 8fcc3ce..8519b17 100644
--- a/media/libstagefright/codecs/aacdec/sbr_dec.cpp
+++ b/media/libstagefright/codecs/aacdec/sbr_dec.cpp
@@ -1,5 +1,5 @@
 /* ------------------------------------------------------------------
- * Copyright (C) 1998-2009 PacketVideo
+ * Copyright (C) 1998-2010 PacketVideo
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -447,7 +447,12 @@
 
             if (xoverBand > sbrDec->highSubband)
             {
-                xoverBand = 32; /* error condition, default to upsampling mode */
+                /*
+                 * error condition, default to upsampling mode
+                 * and make sure that the number of bands for xover does
+                 * not exceed the number of high freq bands.
+                 */
+                xoverBand = (sbrDec->highSubband > 32)? 32: sbrDec->highSubband;
             }
 
             m = sbrDec->bufReadOffs + i;    /*  2 + i */
@@ -558,18 +563,22 @@
         /*
          *  Set Circular buffer for PS hybrid analysis
          */
+
+        int32_t *pt_temp = &scratch_mem[2][32];
+
         for (i = 0, j = 0; i < 3; i++)
         {
 
-            pv_memmove(&scratch_mem[2][32 + j     ],
+            pv_memmove(&pt_temp[ j],
                        hParametricStereoDec->hHybrid->mQmfBufferReal[i],
                        HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferReal));
-            pv_memmove(&scratch_mem[2][32 + j + 44],
+            pv_memmove(&pt_temp[ j + 44],
                        hParametricStereoDec->hHybrid->mQmfBufferImag[i],
                        HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferImag));
             j += 88;
         }
 
+
         pv_memset((void *)&qmf_PS_generated_Real[hParametricStereoDec->usb],
                   0,
                   (64 - hParametricStereoDec->usb)*sizeof(*qmf_PS_generated_Real));
@@ -626,19 +635,23 @@
          *  Save Circular buffer history used on PS hybrid analysis
          */
 
+
+        pt_temp = &scratch_mem[2][64];
+
         for (i = 0, j = 0; i < 3; i++)
         {
             pv_memmove(hParametricStereoDec->hHybrid->mQmfBufferReal[i],
-                       &scratch_mem[2][ 64 + j     ],
+                       &pt_temp[ j],
                        HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferReal));
 
             pv_memmove(hParametricStereoDec->hHybrid->mQmfBufferImag[i],
-                       &scratch_mem[2][ 64 + j + 44],
+                       &pt_temp[ j + 44],
                        HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferImag));
 
             j += 88;
         }
 
+
         pv_memmove(hFrameData->V, &circular_buffer_s[0], 1152*sizeof(*circular_buffer_s));
 
         /*
@@ -746,7 +759,12 @@
 
                 if (xoverBand > sbrDec->highSubband)
                 {
-                    xoverBand = 32; /* error condition, default to upsampling mode */
+                    /*
+                     * error condition, default to upsampling mode
+                     * and make sure that the number of bands for xover does
+                     * not exceed the number of high freq bands.
+                     */
+                    xoverBand = (sbrDec->highSubband > 32)? 32: sbrDec->highSubband;
                 }
             }
             else
diff --git a/media/libstagefright/codecs/aacenc/Android.mk b/media/libstagefright/codecs/aacenc/Android.mk
index cda4f9d..f9cc6a3 100644
--- a/media/libstagefright/codecs/aacenc/Android.mk
+++ b/media/libstagefright/codecs/aacenc/Android.mk
@@ -2,7 +2,7 @@
 include $(CLEAR_VARS)
 include frameworks/base/media/libstagefright/codecs/common/Config.mk
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_SRC_FILES := basic_op/basicop2.c basic_op/oper_32b.c
 
diff --git a/media/libstagefright/codecs/amrnb/dec/AMRNBDecoder.cpp b/media/libstagefright/codecs/amrnb/dec/AMRNBDecoder.cpp
index fb300da..a11d46b 100644
--- a/media/libstagefright/codecs/amrnb/dec/AMRNBDecoder.cpp
+++ b/media/libstagefright/codecs/amrnb/dec/AMRNBDecoder.cpp
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+//#define LOG_NDEBUG 0
+#define LOG_TAG "AMRNBDecoder"
+#include <utils/Log.h>
+
 #include "AMRNBDecoder.h"
 
 #include "gsmamr_dec.h"
@@ -154,18 +158,24 @@
     const uint8_t *inputPtr =
         (const uint8_t *)mInputBuffer->data() + mInputBuffer->range_offset();
 
-    size_t numBytesRead =
+    int32_t numBytesRead =
         AMRDecode(mState,
           (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f),
           (UWord8 *)&inputPtr[1],
           static_cast<int16_t *>(buffer->data()),
           MIME_IETF);
 
+    if (numBytesRead == -1 ) {
+        LOGE("PV AMR decoder AMRDecode() call failed");
+        buffer->release();
+        buffer = NULL;
+        return ERROR_MALFORMED;
+    }
     ++numBytesRead;  // Include the frame type header byte.
 
     buffer->set_range(0, kNumSamplesPerFrame * sizeof(int16_t));
 
-    if (numBytesRead > mInputBuffer->range_length()) {
+    if (static_cast<size_t>(numBytesRead) > mInputBuffer->range_length()) {
         // This is bad, should never have happened, but did. Abort now.
 
         buffer->release();
diff --git a/media/libstagefright/codecs/amrwbenc/Android.mk b/media/libstagefright/codecs/amrwbenc/Android.mk
index 4293287..5179380 100644
--- a/media/libstagefright/codecs/amrwbenc/Android.mk
+++ b/media/libstagefright/codecs/amrwbenc/Android.mk
@@ -2,7 +2,7 @@
 include $(CLEAR_VARS)
 include frameworks/base/media/libstagefright/codecs/common/Config.mk
 
-LOCAL_PRELINK_MODULE := false
+
  	
 LOCAL_SRC_FILES := \
 	AMRWBEncoder.cpp \
diff --git a/media/libstagefright/codecs/common/Android.mk b/media/libstagefright/codecs/common/Android.mk
index fffb2ad..af8795a 100644
--- a/media/libstagefright/codecs/common/Android.mk
+++ b/media/libstagefright/codecs/common/Android.mk
@@ -1,7 +1,7 @@
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_PRELINK_MODULE := false
+
 
 LOCAL_SRC_FILES := cmnMemory.c
 
diff --git a/media/libstagefright/foundation/Android.mk b/media/libstagefright/foundation/Android.mk
index 4e07f6f..d5025a1 100644
--- a/media/libstagefright/foundation/Android.mk
+++ b/media/libstagefright/foundation/Android.mk
@@ -25,6 +25,6 @@
 
 LOCAL_MODULE:= libstagefright_foundation
 
-LOCAL_PRELINK_MODULE:= false
+
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/yuv/Android.mk b/media/libstagefright/yuv/Android.mk
index 7697e3c..a4253f6 100644
--- a/media/libstagefright/yuv/Android.mk
+++ b/media/libstagefright/yuv/Android.mk
@@ -10,6 +10,6 @@
 
 LOCAL_MODULE:= libstagefright_yuv
 
-LOCAL_PRELINK_MODULE := false
+
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/media/mtp/MtpDevice.cpp b/media/mtp/MtpDevice.cpp
index 4ea8849..2e86159 100644
--- a/media/mtp/MtpDevice.cpp
+++ b/media/mtp/MtpDevice.cpp
@@ -819,6 +819,10 @@
         return mResponse.getResponseCode();
     }
     int ret = mResponse.read(mRequestIn1);
+    // handle zero length packets, which might occur if the data transfer
+    // ends on a packet boundary
+    if (ret == 0)
+        ret = mResponse.read(mRequestIn1);
     if (ret >= MTP_CONTAINER_HEADER_SIZE) {
         mResponse.dump();
         return mResponse.getResponseCode();