一.先从Serialize说起       我们都知道JAVA中的Serialize机制,译成串行化、序列化……,其作用是能将数据对象存入字节流当中,在需要时重新生成对象。主要应用是利用外部存储设备保存对象状态,以及通过网络传输对象等。

       二.Android中的新的序列化机制       在Android系统中,定位为针对内存受限的设备,因此对性能要求更高,另外系统中采用了新的IPC(进程间通信)机制,必然要求使用性能更出色的对象传输方式。在这样的环境下,Parcel被设计出来,其定位就是轻量级的高效的对象序列化和反序列化机制。

       三.Parcel类的背后       在Framework中有parcel类,源码路径是:Frameworks/base/core/java/android/os/Parcel.java
       典型的源码片断如下:

java代码:


1. /**
2. * Write an integer value into the parcel at the current dataPosition(),
3. * growing dataCapacity() if needed.
4. */
5. public final native void writeInt(int val); 
6. 
7. /**
8. * Write a long integer value into the parcel at the current dataPosition(),
9. * growing dataCapacity() if needed.
10. */
11. public final native void writeLong(long val);

复制代码



        从中我们看到,从这个源程序文件中我们看不到真正的功能是如何实现的,必须透过JNI往下走了。于是,Frameworks/base/core/jni/android_util_Binder.cpp中找到了线索



java代码:

1. static void android_os_Parcel_writeInt(JNIEnv* env, jobject clazz, jint val)
2. {
3. Parcel* parcel = parcelForJavaObject(env, clazz);
4. if (parcel != NULL) {
5. const status_t err = parcel->writeInt32(val);
6. if (err != NO_ERROR) {
7. jniThrowException(env, “java/lang/OutOfMemoryError”, NULL);
8. }
9. }
10. } 
11. 
12. static void android_os_Parcel_writeLong(JNIEnv* env, jobject clazz, jlong val)
13. {
14. Parcel* parcel = parcelForJavaObject(env, clazz);
15. if (parcel != NULL) {
16. const status_t err = parcel->writeInt64(val);
17. if (err != NO_ERROR) {
18. jniThrowException(env, “java/lang/OutOfMemoryError”, NULL);
19. }
20. }
21. }


复制代码



       从这里我们可以得到的信息是函数的实现依赖于Parcel指针,因此还需要找到Parcel的类定义,注意,这里的类已经是用C++语言实现的了。



       找到Frameworks/base/include/binder/parcel.h和Frameworks/base/libs/binder/parcel.cpp。终于找到了最终的实现代码了。



       有兴趣的朋友可以自己读一下,不难理解,这里把基本的思路总结一下:



       1. 整个读写全是在内存中进行,主要是通过malloc()、realloc()、memcpy()等内存操作进行,所以效率比JAVA序列化中使用外部存储器会高很多;


       2. 读写时是4字节对齐的,可以看到#define PAD_SIZE(s) (((s)+3)&~3)这句宏定义就是在做这件事情;


       3. 如果预分配的空间不够时newSize = ((mDataSize+len)*3)/2;会一次多分配50%;


       4. 对于普通数据,使用的是mData内存地址,对于IBinder类型的数据以及FileDescriptor使用的是mObjects内存地址。后者是通过flatten_binder()和unflatten_binder()实现的,目的是反序列化时读出的对象就是原对象而不用重新new一个新对象。



java代码:

1. /*
2. * Copyright (C) 2005 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. 
17. #ifndef ANDROID_PARCEL_H
18. #define ANDROID_PARCEL_H 
19. 
20. #include 
21. #include 
22. #include 
23. #include 
24. #include 
25. // —————————————————————————
26. namespace android { 
27. 
28. class IBinder;
29. class ProcessState;
30. class String8;
31. class TextOutput;
32. class Flattenable; 
33. 
34. struct flat_binder_object; // defined in support_p/binder_module.h 
35. 
36. class Parcel
37. {
38. public:
39. Parcel();
40. ~Parcel(); 
41. 
42. const uint8_t* data() const;
43. size_t dataSize() const;
44. size_t dataAvail() const;
45. size_t dataPosition() const;
46. size_t dataCapacity() const; 
47. 
48. status_t setDataSize(size_t size);
49. void setDataPosition(size_t pos) const;
50. status_t setDataCapacity(size_t size); 
51. 
52. status_t setData(const uint8_t* buffer, size_t len); 
53. 
54. status_t appendFrom(Parcel *parcel, size_t start, size_t len); 
55. 
56. bool hasFileDescriptors() const;


复制代码


 




本帖最后由 nuli 于 2011-9-14 15:15 编辑


java代码:



    1. status_t writeInterfaceToken(const String16& interface);
    2. bool enforceInterface(const String16& interface) const;
    3. bool checkInterface(IBinder*) const; 
    4. 
    5. void freeData(); 
    6. 
    7. const size_t* objects() const;
    8. size_t objectsCount() const; 
    9. 
    10. status_t errorCheck() const;
    11. void setError(status_t err); 
    12. 
    13. status_t write(const void* data, size_t len);
    14. void* writeInplace(size_t len);
    15. status_t writeUnpadded(const void* data, size_t len);
    16. status_t writeInt32(int32_t val);
    17. status_t writeInt64(int64_t val);
    18. status_t writeFloat(float val);
    19. status_t writeDouble(double val);
    20. status_t writeIntPtr(intptr_t val);
    21. status_t writeCString(const char* str);
    22. status_t writeString8(const String8& str);
    23. status_t writeString16(const String16& str);
    24. status_t writeString16(const char16_t* str, size_t len);
    25. status_t writeStrongBinder(const sp& val);
    26. status_t writeWeakBinder(const wp& val);
    27. status_t write(const Flattenable& val); 
    28. 
    29. // Place a native_handle into the parcel (the native_handle’s file-
    30. // descriptors are dup’ed, so it is safe to delete the native_handle
    31. // when this function returns).
    32. // Doesn’t take ownership of the native_handle.
    33. status_t writeNativeHandle(const native_handle* handle); 
    34. 
    35. // Place a file descriptor into the parcel. The given fd must remain
    36. // valid for the lifetime of the parcel.
    37. status_t writeFileDescriptor(int fd); 
    38. 
    39. // Place a file descriptor into the parcel. A dup of the fd is made, which
    40. // will be closed once the parcel is destroyed.
    41. status_t writeDupFileDescriptor(int fd); 
    42. 
    43. status_t writeObject(const flat_binder_object& val, bool nullMetaData); 
    44. 
    45. void remove(size_t start, size_t amt); 
    46. 
    47. status_t read(void* outData, size_t len) const;
    48. const void* readInplace(size_t len) const;
    49. int32_t readInt32() const;
    50. status_t readInt32(int32_t *pArg) const;
    51. int64_t readInt64() const;
    52. status_t readInt64(int64_t *pArg) const;
    53. float readFloat() const;
    54. status_t readFloat(float *pArg) const;
    55. double readDouble() const;
    56. status_t readDouble(double *pArg) const;
    57. intptr_t readIntPtr() const;
    58. status_t readIntPtr(intptr_t *pArg) const; 
    59. 
    60. const char* readCString() const;
    61. String8 readString8() const;
    62. String16 readString16() const;
    63. const char16_t* readString16Inplace(size_t* outLen) const;
    64. sp readStrongBinder() const;
    65. wp readWeakBinder() const;
    66. status_t read(Flattenable& val) const; 
    67. 
    68. // Retrieve native_handle from the parcel. This returns a copy of the
    69. // parcel’s native_handle (the caller takes ownership). The caller
    70. // must free the native_handle with native_handle_close() and
    71. // native_handle_delete().
    72. native_handle* readNativeHandle() const; 
    73. 
    74. // Retrieve a file descriptor from the parcel. This returns the raw fd
    75. // in the parcel, which you do not own — use dup() to get your own copy.
    76. int readFileDescriptor() const; 
    77. 
    78. const flat_binder_object* readObject(bool nullMetaData) const; 
    79. 
    80. // Explicitly close all file descriptors in the parcel.
    81. void closeFileDescriptors(); 
    82. 
    83. typedef void (*release_func)(Parcel* parcel,
    84. const uint8_t* data, size_t dataSize,
    85. const size_t* objects, size_t objectsSize,
    86. void* cookie); 
    87. 
    88. const uint8_t* ipcData() const;
    89. size_t ipcDataSize() const;
    90. const size_t* ipcObjects() const;
    91. size_t ipcObjectsCount() const;
    92. void ipcSetDataReference(const uint8_t* data, size_t dataSize,
    93. const size_t* objects, size_t objectsCount,
    94. release_func relFunc, void* relCookie); 
    95. 
    96. void print(TextOutput& to, uint32_t flags = 0) const; 
    97. 
    98. private:
    99. Parcel(const Parcel& o);
    100. Parcel& operator=(const Parcel& o); 
    101. 
    102. status_t finishWrite(size_t len);
    103. void releaseObjects();
    104. void acquireObjects();
    105. status_t growData(size_t len);
    106. status_t restartWrite(size_t desired);
    107. status_t continueWrite(size_t desired);
    108. void freeDataNoInit();
    109. void initState();
    110. void scanForFds() const; 
    111. 
    112. template
    113. status_t readAligned(T *pArg) const; 
    114. 
    115. template T readAligned() const; 
    116. 
    117. template
    118. status_t writeAligned(T val); 
    119. 
    120. status_t mError;
    121. uint8_t* mData;
    122. size_t mDataSize;
    123. size_t mDataCapacity;
    124. mutable size_t mDataPos;
    125. size_t* mObjects;
    126. size_t mObjectsSize;
    127. size_t mObjectsCapacity;
    128. mutable size_t mNextObjectHint; 
    129. 
    130. mutable bool mFdsKnown;
    131. mutable bool mHasFds; 
    132. 
    133. release_func mOwner;
    134. void* mOwnerCookie;
    135. }; 
    136.


    复制代码






    本帖最后由 nuli 于 2011-9-14 15:15 编辑

    java代码:

    
      // ————————————————————————— 
    
     inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel)
     {
     parcel.print(to);
     return to;
     } 
    
     // --------------------------------------------------------------------------- 
    
     // Generic acquire and release of objects.
     void acquire_object(const sp& proc,
     const flat_binder_object& obj, const void* who);
     void release_object(const sp& proc,
     const flat_binder_object& obj, const void* who); 
    
     void flatten_binder(const sp& proc,
     const sp& binder, flat_binder_object* out);
     void flatten_binder(const sp& proc,
     const wp& binder, flat_binder_object* out);
     status_t unflatten_binder(const sp& proc,
     const flat_binder_object& flat, sp* out);
     status_t unflatten_binder(const sp& proc,
     const flat_binder_object& flat, wp* out); 
    
     }; // namespace android 
    
     // ————————————————————————— 
    
     #endif // ANDROID_PARCEL_H 
    
     view plain
     /*
     * Copyright (C) 2005 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.
     */ 
    
     #define LOG_TAG “Parcel”
     //#define LOG_NDEBUG 0 
    
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #include 
     #ifndef INT32_MAX
     #define INT32_MAX ((int32_t)(2147483647))
     #endif 
    
     #define LOG_REFS(…)
     //#define LOG_REFS(…) LOG(LOG_DEBUG, “Parcel”, __VA_ARGS__) 
    
     // ————————————————————————— 
    
     #define PAD_SIZE(s) (((s)+3)&~3) 
    
     // XXX This can be made public if we want to provide
     // support for typed data.
     struct small_flat_data
     {
     uint32_t type;
     uint32_t data;
     }; 
    
     namespace android { 
    
     void acquire_object(const sp& proc,
     const flat_binder_object& obj, const void* who)
     {
     switch (obj.type) {
     case BINDER_TYPE_BINDER:
     if (obj.binder) {
     LOG_REFS(“Parcel %p acquiring reference on local %p”, who, obj.cookie);
     static_cast(obj.cookie)->incStrong(who);
     }
     return;
     case BINDER_TYPE_WEAK_BINDER:
     if (obj.binder)
     static_cast(obj.binder)->incWeak(who);
     return;
     case BINDER_TYPE_HANDLE: {
     const sp b = proc->getStrongProxyForHandle(obj.handle);
     if (b != NULL) {
     LOG_REFS(“Parcel %p acquiring reference on remote %p”, who, b.get());
     b->incStrong(who);
     }
     return;
     }
     case BINDER_TYPE_WEAK_HANDLE: {
     const wp b = proc->getWeakProxyForHandle(obj.handle);
     if (b != NULL) b.get_refs()->incWeak(who);
     return;
     }
     case BINDER_TYPE_FD: {
     // intentionally blank — nothing to do to acquire this, but we do
     // recognize it as a legitimate object type.
     return;
     }
     } 
    
     LOGD(“Invalid object type 0x%08lx”, obj.type);
     } 
    
     void release_object(const sp& proc,
     const flat_binder_object& obj, const void* who)
     {
     switch (obj.type) {
     case BINDER_TYPE_BINDER:
     if (obj.binder) {
     LOG_REFS(“Parcel %p releasing reference on local %p”, who, obj.cookie);
     static_cast(obj.cookie)->decStrong(who);
     }
     return;
     case BINDER_TYPE_WEAK_BINDER:
     if (obj.binder)
     static_cast(obj.binder)->decWeak(who);
     return;
     case BINDER_TYPE_HANDLE: {
     const sp b = proc->getStrongProxyForHandle(obj.handle);
     if (b != NULL) {
     LOG_REFS(“Parcel %p releasing reference on remote %p”, who, b.get());
     b->decStrong(who);
     }
     return;
     }
     case BINDER_TYPE_WEAK_HANDLE: {
     const wp b = proc->getWeakProxyForHandle(obj.handle);
     if (b != NULL) b.get_refs()->decWeak(who);
     return;
     }
     case BINDER_TYPE_FD: {
     if (obj.cookie != (void*)0) close(obj.handle);
     return;
     }
     } 
    
     LOGE(“Invalid object type 0x%08lx”, obj.type);
     } 
    
     inline static status_t finish_flatten_binder(
     const sp& binder, const flat_binder_object& flat, Parcel* out)
     {
     return out->writeObject(flat, false);
     } 
    
     status_t flatten_binder(const sp& proc,
     const sp& binder, Parcel* out)
     {
     flat_binder_object obj; 
    
     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
     if (binder != NULL) {
     IBinder *local = binder->localBinder();
     if (!local) {
     BpBinder *proxy = binder->remoteBinder();
     if (proxy == NULL) {
     LOGE(“null proxy”);
     }
     const int32_t handle = proxy ? proxy->handle() : 0;
     obj.type = BINDER_TYPE_HANDLE;
     obj.handle = handle;
     obj.cookie = NULL;
     } else {
     obj.type = BINDER_TYPE_BINDER;
     obj.binder = local->getWeakRefs();
     obj.cookie = local;
     }
     } else {
     obj.type = BINDER_TYPE_BINDER;
     obj.binder = NULL;
     obj.cookie = NULL;
     } 
    
     return finish_flatten_binder(binder, obj, out);
     } 
    
     status_t flatten_binder(const sp& proc,
     const wp& binder, Parcel* out)
     {
     flat_binder_object obj; 
    
     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
     if (binder != NULL) {
     sp real = binder.promote();
     if (real != NULL) {
     IBinder *local = real->localBinder();
     if (!local) {
     BpBinder *proxy = real->remoteBinder();
     if (proxy == NULL) {
     LOGE(“null proxy”);
     }
     const int32_t handle = proxy ? proxy->handle() : 0;
     obj.type = BINDER_TYPE_WEAK_HANDLE;
     obj.handle = handle;
     obj.cookie = NULL;
     } else {
     obj.type = BINDER_TYPE_WEAK_BINDER;
     obj.binder = binder.get_refs();
     obj.cookie = binder.unsafe_get();
     }
     return finish_flatten_binder(real, obj, out);
     }


    复制代码

    java代码:

    
       // XXX How to deal? In order to flatten the given binder,
     // we need to probe it for information, which requires a primary
     // reference… but we don’t have one.
     //
     // The OpenBinder implementation uses a dynamic_cast<> here,
     // but we can’t do that with the different reference counting
     // implementation we are using.
     LOGE(“Unable to unflatten Binder weak reference!”);
     obj.type = BINDER_TYPE_BINDER;
     obj.binder = NULL;
     obj.cookie = NULL;
     return finish_flatten_binder(NULL, obj, out); 
    
     } else {
     obj.type = BINDER_TYPE_BINDER;
     obj.binder = NULL;
     obj.cookie = NULL;
     return finish_flatten_binder(NULL, obj, out);
     }
     } 
    
     inline static status_t finish_unflatten_binder(
     BpBinder* proxy, const flat_binder_object& flat, const Parcel& in)
     {
     return NO_ERROR;
     } 
    
     status_t unflatten_binder(const sp& proc,
     const Parcel& in, sp* out)
     {
     const flat_binder_object* flat = in.readObject(false); 
    
     if (flat) {
     switch (flat->type) {
     case BINDER_TYPE_BINDER:
     *out = static_cast(flat->cookie);
     return finish_unflatten_binder(NULL, *flat, in);
     case BINDER_TYPE_HANDLE:
     *out = proc->getStrongProxyForHandle(flat->handle);
     return finish_unflatten_binder(
     static_cast(out->get()), *flat, in);
     }
     }
     return BAD_TYPE;
     } 
    
     status_t unflatten_binder(const sp& proc,
     const Parcel& in, wp* out)
     {
     const flat_binder_object* flat = in.readObject(false); 
    
     if (flat) {
     switch (flat->type) {
     case BINDER_TYPE_BINDER:
     *out = static_cast(flat->cookie);
     return finish_unflatten_binder(NULL, *flat, in);
     case BINDER_TYPE_WEAK_BINDER:
     if (flat->binder != NULL) {
     out->set_object_and_refs(
     static_cast(flat->cookie),
     static_cast(flat->binder));
     } else {
     *out = NULL;
     }
     return finish_unflatten_binder(NULL, *flat, in);
     case BINDER_TYPE_HANDLE:
     case BINDER_TYPE_WEAK_HANDLE:
     *out = proc->getWeakProxyForHandle(flat->handle);
     return finish_unflatten_binder(
     static_cast(out->unsafe_get()), *flat, in);
     }
     }
     return BAD_TYPE;
     } 
    
     // ————————————————————————— 
    
     Parcel::Parcel()
     {
     initState();
     } 
    
     Parcel::~Parcel()
     {
     freeDataNoInit();
     } 
    
     const uint8_t* Parcel::data() const
     {
     return mData;
     } 
    
     size_t Parcel::dataSize() const
     {
     return (mDataSize > mDataPos ? mDataSize : mDataPos);
     } 
    
     size_t Parcel::dataAvail() const
     {
     // TODO: decide what to do about the possibility that this can
     // report an available-data size that exceeds a Java int’s max
     // positive value, causing havoc. Fortunately this will only
     // happen if someone constructs a Parcel containing more than two
     // gigabytes of data, which on typical phone hardware is simply
     // not possible.
     return dataSize() – dataPosition();
     } 
    
     size_t Parcel::dataPosition() const
     {
     return mDataPos;
     } 
    
     size_t Parcel::dataCapacity() const
     {
     return mDataCapacity;
     } 
    
     status_t Parcel::setDataSize(size_t size)
     {
     status_t err;
     err = continueWrite(size);
     if (err == NO_ERROR) {
     mDataSize = size;
     LOGV(“setDataSize Setting data size of %p to %d/n”, this, mDataSize);
     }
     return err;
     } 
    
     void Parcel::setDataPosition(size_t pos) const
     {
     mDataPos = pos;
     mNextObjectHint = 0;
     } 
    
     status_t Parcel::setDataCapacity(size_t size)
     {
     if (size > mDataSize) return continueWrite(size);
     return NO_ERROR;
     } 
    
     status_t Parcel::setData(const uint8_t* buffer, size_t len)
     {
     status_t err = restartWrite(len);
     if (err == NO_ERROR) {
     memcpy(const_cast(data()), buffer, len);
     mDataSize = len;
     mFdsKnown = false;
     }
     return err;
     } 
    
     status_t Parcel::appendFrom(Parcel *parcel, size_t offset, size_t len)
     {
     const sp proc(ProcessState::self());
     status_t err;
     uint8_t *data = parcel->mData;
     size_t *objects = parcel->mObjects;
     size_t size = parcel->mObjectsSize;
     int startPos = mDataPos;
     int firstIndex = -1, lastIndex = -2; 
    
     if (len == 0) {
     return NO_ERROR;
     } 
    
     // range checks against the source parcel size
     if ((offset > parcel->mDataSize)
     || (len > parcel->mDataSize)
     || (offset + len > parcel->mDataSize)) {
     return BAD_VALUE;
     }


    复制代码




    本帖最后由 nuli 于 2011-9-14 15:13 编辑

    java代码:


    
        // Count objects in range
     for (int i = 0; i < (int) size; i++) {
     size_t off = objects[i];
     if ((off >= offset) && (off < offset + len)) {
     if (firstIndex == -1) {
     firstIndex = i;
     }
     lastIndex = i;
     }
     }
     int numObjects = lastIndex - firstIndex + 1; 
    
     // grow data
     err = growData(len);
     if (err != NO_ERROR) {
     return err;
     } 
    
     // append data
     memcpy(mData + mDataPos, data + offset, len);
     mDataPos += len;
     mDataSize += len; 
    
     if (numObjects > 0) {
     // grow objects
     if (mObjectsCapacity < mObjectsSize + numObjects) {
     int newSize = ((mObjectsSize + numObjects)*3)/2;
     size_t *objects =
     (size_t*)realloc(mObjects, newSize*sizeof(size_t));
     if (objects == (size_t*)0) {
     return NO_MEMORY;
     }
     mObjects = objects;
     mObjectsCapacity = newSize;
     } 
    
     // append and acquire objects
     int idx = mObjectsSize;
     for (int i = firstIndex; i <= lastIndex; i++) {
     size_t off = objects[i] - offset + startPos;
     mObjects[idx++] = off;
     mObjectsSize++; 
    
     flat_binder_object* flat
     = reinterpret_cast(mData + off);
     acquire_object(proc, *flat, this); 
    
     if (flat->type == BINDER_TYPE_FD) {
     // If this is a file descriptor, we need to dup it so the
     // new Parcel now owns its own fd, and can declare that we
     // officially know we have fds.
     flat->handle = dup(flat->handle);
     flat->cookie = (void*)1;
     mHasFds = mFdsKnown = true;
     }
     }
     } 
    
     return NO_ERROR;
     } 
    
     bool Parcel::hasFileDescriptors() const
     {
     if (!mFdsKnown) {
     scanForFds();
     }
     return mHasFds;
     } 
    
     status_t Parcel::writeInterfaceToken(const String16& interface)
     {
     // currently the interface identification token is just its name as a string
     return writeString16(interface);
     } 
    
     bool Parcel::checkInterface(IBinder* binder) const
     {
     return enforceInterface(binder->getInterfaceDescriptor());
     } 
    
     bool Parcel::enforceInterface(const String16& interface) const
     {
     const String16 str(readString16());
     if (str == interface) {
     return true;
     } else {
     LOGW(“**** enforceInterface() expected ‘%s’ but read ‘%s’/n”,
     String8(interface).string(), String8(str).string());
     return false;
     }
     } 
    
     const size_t* Parcel::objects() const
     {
     return mObjects;
     } 
    
     size_t Parcel::objectsCount() const
     {
     return mObjectsSize;
     } 
    
     status_t Parcel::errorCheck() const
     {
     return mError;
     } 
    
     void Parcel::setError(status_t err)
     {
     mError = err;
     } 
    
     status_t Parcel::finishWrite(size_t len)
     {
     //printf(“Finish write of %d/n”, len);
     mDataPos += len;
     LOGV(“finishWrite Setting data pos of %p to %d/n”, this, mDataPos);
     if (mDataPos > mDataSize) {
     mDataSize = mDataPos;
     LOGV(“finishWrite Setting data size of %p to %d/n”, this, mDataSize);
     }
     //printf(“New pos=%d, size=%d/n”, mDataPos, mDataSize);
     return NO_ERROR;
     } 
    
     status_t Parcel::writeUnpadded(const void* data, size_t len)
     {
     size_t end = mDataPos + len;
     if (end < mDataPos) {
     // integer overflow
     return BAD_VALUE;
     } 
     if (end <= mDataCapacity) {
     restart_write:
     memcpy(mData+mDataPos, data, len);
     return finishWrite(len);
     } 
     status_t err = growData(len);
     if (err == NO_ERROR) goto restart_write;
     return err;
     } 
     status_t Parcel::write(const void* data, size_t len)
     {
     void* const d = writeInplace(len);
     if (d) {
     memcpy(d, data, len);
     return NO_ERROR;
     }
     return mError;
     } 
     void* Parcel::writeInplace(size_t len)
     {
     const size_t padded = PAD_SIZE(len); 
     // sanity check for integer overflow
     if (mDataPos+padded < mDataPos) {
     return NULL;
     } 
     if ((mDataPos+padded) <= mDataCapacity) {
     restart_write:
     //printf("Writing %ld bytes, padded to %ld/n", len, padded);
     uint8_t* const data = mData+mDataPos; 
     // Need to pad at end?
     if (padded != len) {
     #if BYTE_ORDER == BIG_ENDIAN
     static const uint32_t mask[4] = {
     0x00000000, 0xffffff00, 0xffff0000, 0xff000000
     };
     #endif
     #if BYTE_ORDER == LITTLE_ENDIAN
     static const uint32_t mask[4] = {
     0x00000000, 0x00ffffff, 0x0000ffff, 0x000000ff
     };
     #endif
     //printf("Applying pad mask: %p to %p/n", (void*)mask[padded-len],
     // *reinterpret_cast(data+padded-4));
     *reinterpret_cast(data+padded-4) &= mask[padded-len];
     }

    复制代码




    本帖最后由 nuli 于 2011-9-14 15:14 编辑

    java代码:


    
         finishWrite(padded);
     return data;
     } 
    
     status_t err = growData(padded);
     if (err == NO_ERROR) goto restart_write;
     return NULL;
     } 
    
     status_t Parcel::writeInt32(int32_t val)
     {
     return writeAligned(val);
     } 
    
     status_t Parcel::writeInt64(int64_t val)
     {
     return writeAligned(val);
     } 
    
     status_t Parcel::writeFloat(float val)
     {
     return writeAligned(val);
     } 
    
     status_t Parcel::writeDouble(double val)
     {
     return writeAligned(val);
     } 
    
     status_t Parcel::writeIntPtr(intptr_t val)
     {
     return writeAligned(val);
     } 
    
     status_t Parcel::writeCString(const char* str)
     {
     return write(str, strlen(str)+1);
     } 
    
     status_t Parcel::writeString8(const String8& str)
     {
     status_t err = writeInt32(str.bytes());
     if (err == NO_ERROR) {
     err = write(str.string(), str.bytes()+1);
     }
     return err;
     } 
    
     status_t Parcel::writeString16(const String16& str)
     {
     return writeString16(str.string(), str.size());
     } 
    
     status_t Parcel::writeString16(const char16_t* str, size_t len)
     {
     if (str == NULL) return writeInt32(-1); 
    
     status_t err = writeInt32(len);
     if (err == NO_ERROR) {
     len *= sizeof(char16_t);
     uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
     if (data) {
     memcpy(data, str, len);
     *reinterpret_cast(data+len) = 0;
     return NO_ERROR;
     }
     err = mError;
     }
     return err;
     } 
    
     status_t Parcel::writeStrongBinder(const sp& val)
     {
     return flatten_binder(ProcessState::self(), val, this);
     } 
    
     status_t Parcel::writeWeakBinder(const wp& val)
     {
     return flatten_binder(ProcessState::self(), val, this);
     } 
    
     status_t Parcel::writeNativeHandle(const native_handle* handle)
     {
     if (!handle || handle->version != sizeof(native_handle))
     return BAD_TYPE; 
    
     status_t err;
     err = writeInt32(handle->numFds);
     if (err != NO_ERROR) return err; 
    
     err = writeInt32(handle->numInts);
     if (err != NO_ERROR) return err; 
    
     for (int i=0 ; err==NO_ERROR && inumFds ; i++)
     err = writeDupFileDescriptor(handle->data[i]); 
    
     if (err != NO_ERROR) {
     LOGD(“write native handle, write dup fd failed”);
     return err;
     }
     err = write(handle->data + handle->numFds, sizeof(int)*handle->numInts);
     return err;
     } 
    
     status_t Parcel::writeFileDescriptor(int fd)
     {
     flat_binder_object obj;
     obj.type = BINDER_TYPE_FD;
     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
     obj.handle = fd;
     obj.cookie = (void*)0;
     return writeObject(obj, true);
     } 
    
     status_t Parcel::writeDupFileDescriptor(int fd)
     {
     flat_binder_object obj;
     obj.type = BINDER_TYPE_FD;
     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
     obj.handle = dup(fd);
     obj.cookie = (void*)1;
     return writeObject(obj, true);
     } 
    
     status_t Parcel::write(const Flattenable& val)
     {
     status_t err; 
    
     // size if needed
     size_t len = val.getFlattenedSize();
     size_t fd_count = val.getFdCount(); 
    
     err = this->writeInt32(len);
     if (err) return err; 
    
     err = this->writeInt32(fd_count);
     if (err) return err; 
    
     // payload
     void* buf = this->writeInplace(PAD_SIZE(len));
     if (buf == NULL)
     return BAD_VALUE; 
    
     int* fds = NULL;
     if (fd_count) {
     fds = new int[fd_count];
     } 
    
     err = val.flatten(buf, len, fds, fd_count);
     for (size_t i=0 ; i err = this->writeDupFileDescriptor( fds[i] );
     } 
    
     if (fd_count) {
     delete [] fds;
     } 
    
     return err;
     } 
    
     status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
     {
     const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
     const bool enoughObjects = mObjectsSize < mObjectsCapacity;
     if (enoughData && enoughObjects) {
     restart_write:
     *reinterpret_cast(mData+mDataPos) = val; 
    
     // Need to write meta-data?
     if (nullMetaData || val.binder != NULL) {
     mObjects[mObjectsSize] = mDataPos;
     acquire_object(ProcessState::self(), val, this);
     mObjectsSize++;
     } 
    
     // remember if it’s a file descriptor
     if (val.type == BINDER_TYPE_FD) {
     mHasFds = mFdsKnown = true;
     } 
    
     return finishWrite(sizeof(flat_binder_object));
     } 
    
     if (!enoughData) {
     const status_t err = growData(sizeof(val));
     if (err != NO_ERROR) return err;
     }
     if (!enoughObjects) {
     size_t newSize = ((mObjectsSize+2)*3)/2;
     size_t* objects = (size_t*)realloc(mObjects, newSize*sizeof(size_t));
     if (objects == NULL) return NO_MEMORY;
     mObjects = objects;
     mObjectsCapacity = newSize;
     }


    复制代码