一.先从Serialize说起

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

二.Android中的新的序列化机制

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

三.Parcel类的背后

在Framework中有parcel类,源码路径是:

Frameworks/base/core/java/android/os/Parcel.java

典型的源码片断如下:

[java] view plain copy print ?
  1. /**
  2. *WriteanintegervalueintotheparcelatthecurrentdataPosition(),
  3. *growingdataCapacity()ifneeded.
  4. */
  5. publicfinalnativevoidwriteInt(intval);
  6. /**
  7. *WritealongintegervalueintotheparcelatthecurrentdataPosition(),
  8. *growingdataCapacity()ifneeded.
  9. */
  10. publicfinalnativevoidwriteLong(longval);
/** * Write an integer value into the parcel at the current dataPosition(), * growing dataCapacity() if needed. */ public final native void writeInt(int val); /** * Write a long integer value into the parcel at the current dataPosition(), * growing dataCapacity() if needed. */ public final native void writeLong(long val);

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

[java] view plain copy print ?
  1. staticvoidandroid_os_Parcel_writeInt(JNIEnv*env,jobjectclazz,jintval)
  2. {
  3. Parcel*parcel=parcelForJavaObject(env,clazz);
  4. if(parcel!=NULL){
  5. conststatus_terr=parcel->writeInt32(val);
  6. if(err!=NO_ERROR){
  7. jniThrowException(env,"java/lang/OutOfMemoryError",NULL);
  8. }
  9. }
  10. }
  11. staticvoidandroid_os_Parcel_writeLong(JNIEnv*env,jobjectclazz,jlongval)
  12. {
  13. Parcel*parcel=parcelForJavaObject(env,clazz);
  14. if(parcel!=NULL){
  15. conststatus_terr=parcel->writeInt64(val);
  16. if(err!=NO_ERROR){
  17. jniThrowException(env,"java/lang/OutOfMemoryError",NULL);
  18. }
  19. }
  20. }
static void android_os_Parcel_writeInt(JNIEnv* env, jobject clazz, jint val){ Parcel* parcel = parcelForJavaObject(env, clazz); if (parcel != NULL) { const status_t err = parcel->writeInt32(val); if (err != NO_ERROR) { jniThrowException(env, "java/lang/OutOfMemoryError", NULL); } }}static void android_os_Parcel_writeLong(JNIEnv* env, jobject clazz, jlong val){ Parcel* parcel = parcelForJavaObject(env, clazz); if (parcel != NULL) { const status_t err = parcel->writeInt64(val); if (err != NO_ERROR) { jniThrowException(env, "java/lang/OutOfMemoryError", NULL); } }}

从这里我们可以得到的信息是函数的实现依赖于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一个新对象。

好了,这就是Parcel背后的动作,全是在一块内存里进行读写操作,就不啰嗦了,把parcel的代码贴在这供没有源码的朋友参考吧。接下来我会用一个小DEMO演示一下Parcel类在应用程序中的使用,详见《探索Android中的Parcel机制(下)》。

[cpp] view plain copy print ?
  1. /*
  2. *Copyright(C)2005TheAndroidOpenSourceProject
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. #ifndefANDROID_PARCEL_H
  17. #defineANDROID_PARCEL_H
  18. #include<cutils/native_handle.h>
  19. #include<utils/Errors.h>
  20. #include<utils/RefBase.h>
  21. #include<utils/String16.h>
  22. #include<utils/Vector.h>
  23. //---------------------------------------------------------------------------
  24. namespaceandroid{
  25. classIBinder;
  26. classProcessState;
  27. classString8;
  28. classTextOutput;
  29. classFlattenable;
  30. structflat_binder_object;//definedinsupport_p/binder_module.h
  31. classParcel
  32. {
  33. public:
  34. Parcel();
  35. ~Parcel();
  36. constuint8_t*data()const;
  37. size_tdataSize()const;
  38. size_tdataAvail()const;
  39. size_tdataPosition()const;
  40. size_tdataCapacity()const;
  41. status_tsetDataSize(size_tsize);
  42. voidsetDataPosition(size_tpos)const;
  43. status_tsetDataCapacity(size_tsize);
  44. status_tsetData(constuint8_t*buffer,size_tlen);
  45. status_tappendFrom(Parcel*parcel,size_tstart,size_tlen);
  46. boolhasFileDescriptors()const;
  47. status_twriteInterfaceToken(constString16&interface);
  48. boolenforceInterface(constString16&interface)const;
  49. boolcheckInterface(IBinder*)const;
  50. voidfreeData();
  51. constsize_t*objects()const;
  52. size_tobjectsCount()const;
  53. status_terrorCheck()const;
  54. voidsetError(status_terr);
  55. status_twrite(constvoid*data,size_tlen);
  56. void*writeInplace(size_tlen);
  57. status_twriteUnpadded(constvoid*data,size_tlen);
  58. status_twriteInt32(int32_tval);
  59. status_twriteInt64(int64_tval);
  60. status_twriteFloat(floatval);
  61. status_twriteDouble(doubleval);
  62. status_twriteIntPtr(intptr_tval);
  63. status_twriteCString(constchar*str);
  64. status_twriteString8(constString8&str);
  65. status_twriteString16(constString16&str);
  66. status_twriteString16(constchar16_t*str,size_tlen);
  67. status_twriteStrongBinder(constsp<IBinder>&val);
  68. status_twriteWeakBinder(constwp<IBinder>&val);
  69. status_twrite(constFlattenable&val);
  70. //Placeanative_handleintotheparcel(thenative_handle'sfile-
  71. //descriptorsaredup'ed,soitissafetodeletethenative_handle
  72. //whenthisfunctionreturns).
  73. //Doesn'ttakeownershipofthenative_handle.
  74. status_twriteNativeHandle(constnative_handle*handle);
  75. //Placeafiledescriptorintotheparcel.Thegivenfdmustremain
  76. //validforthelifetimeoftheparcel.
  77. status_twriteFileDescriptor(intfd);
  78. //Placeafiledescriptorintotheparcel.Adupofthefdismade,which
  79. //willbeclosedoncetheparcelisdestroyed.
  80. status_twriteDupFileDescriptor(intfd);
  81. status_twriteObject(constflat_binder_object&val,boolnullMetaData);
  82. voidremove(size_tstart,size_tamt);
  83. status_tread(void*outData,size_tlen)const;
  84. constvoid*readInplace(size_tlen)const;
  85. int32_treadInt32()const;
  86. status_treadInt32(int32_t*pArg)const;
  87. int64_treadInt64()const;
  88. status_treadInt64(int64_t*pArg)const;
  89. floatreadFloat()const;
  90. status_treadFloat(float*pArg)const;
  91. doublereadDouble()const;
  92. status_treadDouble(double*pArg)const;
  93. intptr_treadIntPtr()const;
  94. status_treadIntPtr(intptr_t*pArg)const;
  95. constchar*readCString()const;
  96. String8readString8()const;
  97. String16readString16()const;
  98. constchar16_t*readString16Inplace(size_t*outLen)const;
  99. sp<IBinder>readStrongBinder()const;
  100. wp<IBinder>readWeakBinder()const;
  101. status_tread(Flattenable&val)const;
  102. //Retrievenative_handlefromtheparcel.Thisreturnsacopyofthe
  103. //parcel'snative_handle(thecallertakesownership).Thecaller
  104. //mustfreethenative_handlewithnative_handle_close()and
  105. //native_handle_delete().
  106. native_handle*readNativeHandle()const;
  107. //Retrieveafiledescriptorfromtheparcel.Thisreturnstherawfd
  108. //intheparcel,whichyoudonotown--usedup()togetyourowncopy.
  109. intreadFileDescriptor()const;
  110. constflat_binder_object*readObject(boolnullMetaData)const;
  111. //Explicitlycloseallfiledescriptorsintheparcel.
  112. voidcloseFileDescriptors();
  113. typedefvoid(*release_func)(Parcel*parcel,
  114. constuint8_t*data,size_tdataSize,
  115. constsize_t*objects,size_tobjectsSize,
  116. void*cookie);
  117. constuint8_t*ipcData()const;
  118. size_tipcDataSize()const;
  119. constsize_t*ipcObjects()const;
  120. size_tipcObjectsCount()const;
  121. voidipcSetDataReference(constuint8_t*data,size_tdataSize,
  122. constsize_t*objects,size_tobjectsCount,
  123. release_funcrelFunc,void*relCookie);
  124. voidprint(TextOutput&to,uint32_tflags=0)const;
  125. private:
  126. Parcel(constParcel&o);
  127. Parcel&operator=(constParcel&o);
  128. status_tfinishWrite(size_tlen);
  129. voidreleaseObjects();
  130. voidacquireObjects();
  131. status_tgrowData(size_tlen);
  132. status_trestartWrite(size_tdesired);
  133. status_tcontinueWrite(size_tdesired);
  134. voidfreeDataNoInit();
  135. voidinitState();
  136. voidscanForFds()const;
  137. template<classT>
  138. status_treadAligned(T*pArg)const;
  139. template<classT>TreadAligned()const;
  140. template<classT>
  141. status_twriteAligned(Tval);
  142. status_tmError;
  143. uint8_t*mData;
  144. size_tmDataSize;
  145. size_tmDataCapacity;
  146. mutablesize_tmDataPos;
  147. size_t*mObjects;
  148. size_tmObjectsSize;
  149. size_tmObjectsCapacity;
  150. mutablesize_tmNextObjectHint;
  151. mutableboolmFdsKnown;
  152. mutableboolmHasFds;
  153. release_funcmOwner;
  154. void*mOwnerCookie;
  155. };
  156. //---------------------------------------------------------------------------
  157. inlineTextOutput&operator<<(TextOutput&to,constParcel&parcel)
  158. {
  159. parcel.print(to);
  160. returnto;
  161. }
  162. //---------------------------------------------------------------------------
  163. //Genericacquireandreleaseofobjects.
  164. voidacquire_object(constsp<ProcessState>&proc,
  165. constflat_binder_object&obj,constvoid*who);
  166. voidrelease_object(constsp<ProcessState>&proc,
  167. constflat_binder_object&obj,constvoid*who);
  168. voidflatten_binder(constsp<ProcessState>&proc,
  169. constsp<IBinder>&binder,flat_binder_object*out);
  170. voidflatten_binder(constsp<ProcessState>&proc,
  171. constwp<IBinder>&binder,flat_binder_object*out);
  172. status_tunflatten_binder(constsp<ProcessState>&proc,
  173. constflat_binder_object&flat,sp<IBinder>*out);
  174. status_tunflatten_binder(constsp<ProcessState>&proc,
  175. constflat_binder_object&flat,wp<IBinder>*out);
  176. };//namespaceandroid
  177. //---------------------------------------------------------------------------
  178. #endif//ANDROID_PARCEL_H
/* * 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. */#ifndef ANDROID_PARCEL_H#define ANDROID_PARCEL_H#include <cutils/native_handle.h>#include <utils/Errors.h>#include <utils/RefBase.h>#include <utils/String16.h>#include <utils/Vector.h>// ---------------------------------------------------------------------------namespace android {class IBinder;class ProcessState;class String8;class TextOutput;class Flattenable;struct flat_binder_object; // defined in support_p/binder_module.hclass Parcel{public: Parcel(); ~Parcel(); const uint8_t* data() const; size_t dataSize() const; size_t dataAvail() const; size_t dataPosition() const; size_t dataCapacity() const; status_t setDataSize(size_t size); void setDataPosition(size_t pos) const; status_t setDataCapacity(size_t size); status_t setData(const uint8_t* buffer, size_t len); status_t appendFrom(Parcel *parcel, size_t start, size_t len); bool hasFileDescriptors() const; status_t writeInterfaceToken(const String16& interface); bool enforceInterface(const String16& interface) const; bool checkInterface(IBinder*) const; void freeData(); const size_t* objects() const; size_t objectsCount() const; status_t errorCheck() const; void setError(status_t err); status_t write(const void* data, size_t len); void* writeInplace(size_t len); status_t writeUnpadded(const void* data, size_t len); status_t writeInt32(int32_t val); status_t writeInt64(int64_t val); status_t writeFloat(float val); status_t writeDouble(double val); status_t writeIntPtr(intptr_t val); status_t writeCString(const char* str); status_t writeString8(const String8& str); status_t writeString16(const String16& str); status_t writeString16(const char16_t* str, size_t len); status_t writeStrongBinder(const sp<IBinder>& val); status_t writeWeakBinder(const wp<IBinder>& val); status_t write(const Flattenable& val); // Place a native_handle into the parcel (the native_handle's file- // descriptors are dup'ed, so it is safe to delete the native_handle // when this function returns). // Doesn't take ownership of the native_handle. status_t writeNativeHandle(const native_handle* handle); // Place a file descriptor into the parcel. The given fd must remain // valid for the lifetime of the parcel. status_t writeFileDescriptor(int fd); // Place a file descriptor into the parcel. A dup of the fd is made, which // will be closed once the parcel is destroyed. status_t writeDupFileDescriptor(int fd); status_t writeObject(const flat_binder_object& val, bool nullMetaData); void remove(size_t start, size_t amt); status_t read(void* outData, size_t len) const; const void* readInplace(size_t len) const; int32_t readInt32() const; status_t readInt32(int32_t *pArg) const; int64_t readInt64() const; status_t readInt64(int64_t *pArg) const; float readFloat() const; status_t readFloat(float *pArg) const; double readDouble() const; status_t readDouble(double *pArg) const; intptr_t readIntPtr() const; status_t readIntPtr(intptr_t *pArg) const; const char* readCString() const; String8 readString8() const; String16 readString16() const; const char16_t* readString16Inplace(size_t* outLen) const; sp<IBinder> readStrongBinder() const; wp<IBinder> readWeakBinder() const; status_t read(Flattenable& val) const; // Retrieve native_handle from the parcel. This returns a copy of the // parcel's native_handle (the caller takes ownership). The caller // must free the native_handle with native_handle_close() and // native_handle_delete(). native_handle* readNativeHandle() const; // Retrieve a file descriptor from the parcel. This returns the raw fd // in the parcel, which you do not own -- use dup() to get your own copy. int readFileDescriptor() const; const flat_binder_object* readObject(bool nullMetaData) const; // Explicitly close all file descriptors in the parcel. void closeFileDescriptors(); typedef void (*release_func)(Parcel* parcel, const uint8_t* data, size_t dataSize, const size_t* objects, size_t objectsSize, void* cookie); const uint8_t* ipcData() const; size_t ipcDataSize() const; const size_t* ipcObjects() const; size_t ipcObjectsCount() const; void ipcSetDataReference(const uint8_t* data, size_t dataSize, const size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie); void print(TextOutput& to, uint32_t flags = 0) const; private: Parcel(const Parcel& o); Parcel& operator=(const Parcel& o); status_t finishWrite(size_t len); void releaseObjects(); void acquireObjects(); status_t growData(size_t len); status_t restartWrite(size_t desired); status_t continueWrite(size_t desired); void freeDataNoInit(); void initState(); void scanForFds() const; template<class T> status_t readAligned(T *pArg) const; template<class T> T readAligned() const; template<class T> status_t writeAligned(T val); status_t mError; uint8_t* mData; size_t mDataSize; size_t mDataCapacity; mutable size_t mDataPos; size_t* mObjects; size_t mObjectsSize; size_t mObjectsCapacity; mutable size_t mNextObjectHint; mutable bool mFdsKnown; mutable bool mHasFds; release_func mOwner; void* mOwnerCookie;};// ---------------------------------------------------------------------------inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel){ parcel.print(to); return to;}// ---------------------------------------------------------------------------// Generic acquire and release of objects.void acquire_object(const sp<ProcessState>& proc, const flat_binder_object& obj, const void* who);void release_object(const sp<ProcessState>& proc, const flat_binder_object& obj, const void* who);void flatten_binder(const sp<ProcessState>& proc, const sp<IBinder>& binder, flat_binder_object* out);void flatten_binder(const sp<ProcessState>& proc, const wp<IBinder>& binder, flat_binder_object* out);status_t unflatten_binder(const sp<ProcessState>& proc, const flat_binder_object& flat, sp<IBinder>* out);status_t unflatten_binder(const sp<ProcessState>& proc, const flat_binder_object& flat, wp<IBinder>* out);}; // namespace android// ---------------------------------------------------------------------------#endif // ANDROID_PARCEL_H

[cpp] view plain copy print ?
  1. /*
  2. *Copyright(C)2005TheAndroidOpenSourceProject
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. #defineLOG_TAG"Parcel"
  17. //#defineLOG_NDEBUG0
  18. #include<binder/Parcel.h>
  19. #include<binder/Binder.h>
  20. #include<binder/BpBinder.h>
  21. #include<utils/Debug.h>
  22. #include<binder/ProcessState.h>
  23. #include<utils/Log.h>
  24. #include<utils/String8.h>
  25. #include<utils/String16.h>
  26. #include<utils/TextOutput.h>
  27. #include<utils/misc.h>
  28. #include<utils/Flattenable.h>
  29. #include<private/binder/binder_module.h>
  30. #include<stdio.h>
  31. #include<stdlib.h>
  32. #include<stdint.h>
  33. #ifndefINT32_MAX
  34. #defineINT32_MAX((int32_t)(2147483647))
  35. #endif
  36. #defineLOG_REFS(...)
  37. //#defineLOG_REFS(...)LOG(LOG_DEBUG,"Parcel",__VA_ARGS__)
  38. //---------------------------------------------------------------------------
  39. #definePAD_SIZE(s)(((s)+3)&~3)
  40. //XXXThiscanbemadepublicifwewanttoprovide
  41. //supportfortypeddata.
  42. structsmall_flat_data
  43. {
  44. uint32_ttype;
  45. uint32_tdata;
  46. };
  47. namespaceandroid{
  48. voidacquire_object(constsp<ProcessState>&proc,
  49. constflat_binder_object&obj,constvoid*who)
  50. {
  51. switch(obj.type){
  52. caseBINDER_TYPE_BINDER:
  53. if(obj.binder){
  54. LOG_REFS("Parcel%pacquiringreferenceonlocal%p",who,obj.cookie);
  55. static_cast<IBinder*>(obj.cookie)->incStrong(who);
  56. }
  57. return;
  58. caseBINDER_TYPE_WEAK_BINDER:
  59. if(obj.binder)
  60. static_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who);
  61. return;
  62. caseBINDER_TYPE_HANDLE:{
  63. constsp<IBinder>b=proc->getStrongProxyForHandle(obj.handle);
  64. if(b!=NULL){
  65. LOG_REFS("Parcel%pacquiringreferenceonremote%p",who,b.get());
  66. b->incStrong(who);
  67. }
  68. return;
  69. }
  70. caseBINDER_TYPE_WEAK_HANDLE:{
  71. constwp<IBinder>b=proc->getWeakProxyForHandle(obj.handle);
  72. if(b!=NULL)b.get_refs()->incWeak(who);
  73. return;
  74. }
  75. caseBINDER_TYPE_FD:{
  76. //intentionallyblank--nothingtodotoacquirethis,butwedo
  77. //recognizeitasalegitimateobjecttype.
  78. return;
  79. }
  80. }
  81. LOGD("Invalidobjecttype0x%08lx",obj.type);
  82. }
  83. voidrelease_object(constsp<ProcessState>&proc,
  84. constflat_binder_object&obj,constvoid*who)
  85. {
  86. switch(obj.type){
  87. caseBINDER_TYPE_BINDER:
  88. if(obj.binder){
  89. LOG_REFS("Parcel%preleasingreferenceonlocal%p",who,obj.cookie);
  90. static_cast<IBinder*>(obj.cookie)->decStrong(who);
  91. }
  92. return;
  93. caseBINDER_TYPE_WEAK_BINDER:
  94. if(obj.binder)
  95. static_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who);
  96. return;
  97. caseBINDER_TYPE_HANDLE:{
  98. constsp<IBinder>b=proc->getStrongProxyForHandle(obj.handle);
  99. if(b!=NULL){
  100. LOG_REFS("Parcel%preleasingreferenceonremote%p",who,b.get());
  101. b->decStrong(who);
  102. }
  103. return;
  104. }
  105. caseBINDER_TYPE_WEAK_HANDLE:{
  106. constwp<IBinder>b=proc->getWeakProxyForHandle(obj.handle);
  107. if(b!=NULL)b.get_refs()->decWeak(who);
  108. return;
  109. }
  110. caseBINDER_TYPE_FD:{
  111. if(obj.cookie!=(void*)0)close(obj.handle);
  112. return;
  113. }
  114. }
  115. LOGE("Invalidobjecttype0x%08lx",obj.type);
  116. }
  117. inlinestaticstatus_tfinish_flatten_binder(
  118. constsp<IBinder>&binder,constflat_binder_object&flat,Parcel*out)
  119. {
  120. returnout->writeObject(flat,false);
  121. }
  122. status_tflatten_binder(constsp<ProcessState>&proc,
  123. constsp<IBinder>&binder,Parcel*out)
  124. {
  125. flat_binder_objectobj;
  126. obj.flags=0x7f|FLAT_BINDER_FLAG_ACCEPTS_FDS;
  127. if(binder!=NULL){
  128. IBinder*local=binder->localBinder();
  129. if(!local){
  130. BpBinder*proxy=binder->remoteBinder();
  131. if(proxy==NULL){
  132. LOGE("nullproxy");
  133. }
  134. constint32_thandle=proxy?proxy->handle():0;
  135. obj.type=BINDER_TYPE_HANDLE;
  136. obj.handle=handle;
  137. obj.cookie=NULL;
  138. }else{
  139. obj.type=BINDER_TYPE_BINDER;
  140. obj.binder=local->getWeakRefs();
  141. obj.cookie=local;
  142. }
  143. }else{
  144. obj.type=BINDER_TYPE_BINDER;
  145. obj.binder=NULL;
  146. obj.cookie=NULL;
  147. }
  148. returnfinish_flatten_binder(binder,obj,out);
  149. }
  150. status_tflatten_binder(constsp<ProcessState>&proc,
  151. constwp<IBinder>&binder,Parcel*out)
  152. {
  153. flat_binder_objectobj;
  154. obj.flags=0x7f|FLAT_BINDER_FLAG_ACCEPTS_FDS;
  155. if(binder!=NULL){
  156. sp<IBinder>real=binder.promote();
  157. if(real!=NULL){
  158. IBinder*local=real->localBinder();
  159. if(!local){
  160. BpBinder*proxy=real->remoteBinder();
  161. if(proxy==NULL){
  162. LOGE("nullproxy");
  163. }
  164. constint32_thandle=proxy?proxy->handle():0;
  165. obj.type=BINDER_TYPE_WEAK_HANDLE;
  166. obj.handle=handle;
  167. obj.cookie=NULL;
  168. }else{
  169. obj.type=BINDER_TYPE_WEAK_BINDER;
  170. obj.binder=binder.get_refs();
  171. obj.cookie=binder.unsafe_get();
  172. }
  173. returnfinish_flatten_binder(real,obj,out);
  174. }
  175. //XXXHowtodeal?Inordertoflattenthegivenbinder,
  176. //weneedtoprobeitforinformation,whichrequiresaprimary
  177. //reference...butwedon'thaveone.
  178. //
  179. //TheOpenBinderimplementationusesadynamic_cast<>here,
  180. //butwecan'tdothatwiththedifferentreferencecounting
  181. //implementationweareusing.
  182. LOGE("UnabletounflattenBinderweakreference!");
  183. obj.type=BINDER_TYPE_BINDER;
  184. obj.binder=NULL;
  185. obj.cookie=NULL;
  186. returnfinish_flatten_binder(NULL,obj,out);
  187. }else{
  188. obj.type=BINDER_TYPE_BINDER;
  189. obj.binder=NULL;
  190. obj.cookie=NULL;
  191. returnfinish_flatten_binder(NULL,obj,out);
  192. }
  193. }
  194. inlinestaticstatus_tfinish_unflatten_binder(
  195. BpBinder*proxy,constflat_binder_object&flat,constParcel&in)
  196. {
  197. returnNO_ERROR;
  198. }
  199. status_tunflatten_binder(constsp<ProcessState>&proc,
  200. constParcel&in,sp<IBinder>*out)
  201. {
  202. constflat_binder_object*flat=in.readObject(false);
  203. if(flat){
  204. switch(flat->type){
  205. caseBINDER_TYPE_BINDER:
  206. *out=static_cast<IBinder*>(flat->cookie);
  207. returnfinish_unflatten_binder(NULL,*flat,in);
  208. caseBINDER_TYPE_HANDLE:
  209. *out=proc->getStrongProxyForHandle(flat->handle);
  210. returnfinish_unflatten_binder(
  211. static_cast<BpBinder*>(out->get()),*flat,in);
  212. }
  213. }
  214. returnBAD_TYPE;
  215. }
  216. status_tunflatten_binder(constsp<ProcessState>&proc,
  217. constParcel&in,wp<IBinder>*out)
  218. {
  219. constflat_binder_object*flat=in.readObject(false);
  220. if(flat){
  221. switch(flat->type){
  222. caseBINDER_TYPE_BINDER:
  223. *out=static_cast<IBinder*>(flat->cookie);
  224. returnfinish_unflatten_binder(NULL,*flat,in);
  225. caseBINDER_TYPE_WEAK_BINDER:
  226. if(flat->binder!=NULL){
  227. out->set_object_and_refs(
  228. static_cast<IBinder*>(flat->cookie),
  229. static_cast<RefBase::weakref_type*>(flat->binder));
  230. }else{
  231. *out=NULL;
  232. }
  233. returnfinish_unflatten_binder(NULL,*flat,in);
  234. caseBINDER_TYPE_HANDLE:
  235. caseBINDER_TYPE_WEAK_HANDLE:
  236. *out=proc->getWeakProxyForHandle(flat->handle);
  237. returnfinish_unflatten_binder(
  238. static_cast<BpBinder*>(out->unsafe_get()),*flat,in);
  239. }
  240. }
  241. returnBAD_TYPE;
  242. }
  243. //---------------------------------------------------------------------------
  244. Parcel::Parcel()
  245. {
  246. initState();
  247. }
  248. Parcel::~Parcel()
  249. {
  250. freeDataNoInit();
  251. }
  252. constuint8_t*Parcel::data()const
  253. {
  254. returnmData;
  255. }
  256. size_tParcel::dataSize()const
  257. {
  258. return(mDataSize>mDataPos?mDataSize:mDataPos);
  259. }
  260. size_tParcel::dataAvail()const
  261. {
  262. //TODO:decidewhattodoaboutthepossibilitythatthiscan
  263. //reportanavailable-datasizethatexceedsaJavaint'smax
  264. //positivevalue,causinghavoc.Fortunatelythiswillonly
  265. //happenifsomeoneconstructsaParcelcontainingmorethantwo
  266. //gigabytesofdata,whichontypicalphonehardwareissimply
  267. //notpossible.
  268. returndataSize()-dataPosition();
  269. }
  270. size_tParcel::dataPosition()const
  271. {
  272. returnmDataPos;
  273. }
  274. size_tParcel::dataCapacity()const
  275. {
  276. returnmDataCapacity;
  277. }
  278. status_tParcel::setDataSize(size_tsize)
  279. {
  280. status_terr;
  281. err=continueWrite(size);
  282. if(err==NO_ERROR){
  283. mDataSize=size;
  284. LOGV("setDataSizeSettingdatasizeof%pto%d/n",this,mDataSize);
  285. }
  286. returnerr;
  287. }
  288. voidParcel::setDataPosition(size_tpos)const
  289. {
  290. mDataPos=pos;
  291. mNextObjectHint=0;
  292. }
  293. status_tParcel::setDataCapacity(size_tsize)
  294. {
  295. if(size>mDataSize)returncontinueWrite(size);
  296. returnNO_ERROR;
  297. }
  298. status_tParcel::setData(constuint8_t*buffer,size_tlen)
  299. {
  300. status_terr=restartWrite(len);
  301. if(err==NO_ERROR){
  302. memcpy(const_cast<uint8_t*>(data()),buffer,len);
  303. mDataSize=len;
  304. mFdsKnown=false;
  305. }
  306. returnerr;
  307. }
  308. status_tParcel::appendFrom(Parcel*parcel,size_toffset,size_tlen)
  309. {
  310. constsp<ProcessState>proc(ProcessState::self());
  311. status_terr;
  312. uint8_t*data=parcel->mData;
  313. size_t*objects=parcel->mObjects;
  314. size_tsize=parcel->mObjectsSize;
  315. intstartPos=mDataPos;
  316. intfirstIndex=-1,lastIndex=-2;
  317. if(len==0){
  318. returnNO_ERROR;
  319. }
  320. //rangechecksagainstthesourceparcelsize
  321. if((offset>parcel->mDataSize)
  322. ||(len>parcel->mDataSize)
  323. ||(offset+len>parcel->mDataSize)){
  324. returnBAD_VALUE;
  325. }
  326. //Countobjectsinrange
  327. for(inti=0;i<(int)size;i++){
  328. size_toff=objects[i];
  329. if((off>=offset)&&(off<offset+len)){
  330. if(firstIndex==-1){
  331. firstIndex=i;
  332. }
  333. lastIndex=i;
  334. }
  335. }
  336. intnumObjects=lastIndex-firstIndex+1;
  337. //growdata
  338. err=growData(len);
  339. if(err!=NO_ERROR){
  340. returnerr;
  341. }
  342. //appenddata
  343. memcpy(mData+mDataPos,data+offset,len);
  344. mDataPos+=len;
  345. mDataSize+=len;
  346. if(numObjects>0){
  347. //growobjects
  348. if(mObjectsCapacity<mObjectsSize+numObjects){
  349. intnewSize=((mObjectsSize+numObjects)*3)/2;
  350. size_t*objects=
  351. (size_t*)realloc(mObjects,newSize*sizeof(size_t));
  352. if(objects==(size_t*)0){
  353. returnNO_MEMORY;
  354. }
  355. mObjects=objects;
  356. mObjectsCapacity=newSize;
  357. }
  358. //appendandacquireobjects
  359. intidx=mObjectsSize;
  360. for(inti=firstIndex;i<=lastIndex;i++){
  361. size_toff=objects[i]-offset+startPos;
  362. mObjects[idx++]=off;
  363. mObjectsSize++;
  364. flat_binder_object*flat
  365. =reinterpret_cast<flat_binder_object*>(mData+off);
  366. acquire_object(proc,*flat,this);
  367. if(flat->type==BINDER_TYPE_FD){
  368. //Ifthisisafiledescriptor,weneedtodupitsothe
  369. //newParcelnowownsitsownfd,andcandeclarethatwe
  370. //officiallyknowwehavefds.
  371. flat->handle=dup(flat->handle);
  372. flat->cookie=(void*)1;
  373. mHasFds=mFdsKnown=true;
  374. }
  375. }
  376. }
  377. returnNO_ERROR;
  378. }
  379. boolParcel::hasFileDescriptors()const
  380. {
  381. if(!mFdsKnown){
  382. scanForFds();
  383. }
  384. returnmHasFds;
  385. }
  386. status_tParcel::writeInterfaceToken(constString16&interface)
  387. {
  388. //currentlytheinterfaceidentificationtokenisjustitsnameasastring
  389. returnwriteString16(interface);
  390. }
  391. boolParcel::checkInterface(IBinder*binder)const
  392. {
  393. returnenforceInterface(binder->getInterfaceDescriptor());
  394. }
  395. boolParcel::enforceInterface(constString16&interface)const
  396. {
  397. constString16str(readString16());
  398. if(str==interface){
  399. returntrue;
  400. }else{
  401. LOGW("****enforceInterface()expected'%s'butread'%s'/n",
  402. String8(interface).string(),String8(str).string());
  403. returnfalse;
  404. }
  405. }
  406. constsize_t*Parcel::objects()const
  407. {
  408. returnmObjects;
  409. }
  410. size_tParcel::objectsCount()const
  411. {
  412. returnmObjectsSize;
  413. }
  414. status_tParcel::errorCheck()const
  415. {
  416. returnmError;
  417. }
  418. voidParcel::setError(status_terr)
  419. {
  420. mError=err;
  421. }
  422. status_tParcel::finishWrite(size_tlen)
  423. {
  424. //printf("Finishwriteof%d/n",len);
  425. mDataPos+=len;
  426. LOGV("finishWriteSettingdataposof%pto%d/n",this,mDataPos);
  427. if(mDataPos>mDataSize){
  428. mDataSize=mDataPos;
  429. LOGV("finishWriteSettingdatasizeof%pto%d/n",this,mDataSize);
  430. }
  431. //printf("Newpos=%d,size=%d/n",mDataPos,mDataSize);
  432. returnNO_ERROR;
  433. }
  434. status_tParcel::writeUnpadded(constvoid*data,size_tlen)
  435. {
  436. size_tend=mDataPos+len;
  437. if(end<mDataPos){
  438. //integeroverflow
  439. returnBAD_VALUE;
  440. }
  441. if(end<=mDataCapacity){
  442. restart_write:
  443. memcpy(mData+mDataPos,data,len);
  444. returnfinishWrite(len);
  445. }
  446. status_terr=growData(len);
  447. if(err==NO_ERROR)gotorestart_write;
  448. returnerr;
  449. }
  450. status_tParcel::write(constvoid*data,size_tlen)
  451. {
  452. void*constd=writeInplace(len);
  453. if(d){
  454. memcpy(d,data,len);
  455. returnNO_ERROR;
  456. }
  457. returnmError;
  458. }
  459. void*Parcel::writeInplace(size_tlen)
  460. {
  461. constsize_tpadded=PAD_SIZE(len);
  462. //sanitycheckforintegeroverflow
  463. if(mDataPos+padded<mDataPos){
  464. returnNULL;
  465. }
  466. if((mDataPos+padded)<=mDataCapacity){
  467. restart_write:
  468. //printf("Writing%ldbytes,paddedto%ld/n",len,padded);
  469. uint8_t*constdata=mData+mDataPos;
  470. //Needtopadatend?
  471. if(padded!=len){
  472. #ifBYTE_ORDER==BIG_ENDIAN
  473. staticconstuint32_tmask[4]={
  474. 0x00000000,0xffffff00,0xffff0000,0xff000000
  475. };
  476. #endif
  477. #ifBYTE_ORDER==LITTLE_ENDIAN
  478. staticconstuint32_tmask[4]={
  479. 0x00000000,0x00ffffff,0x0000ffff,0x000000ff
  480. };
  481. #endif
  482. //printf("Applyingpadmask:%pto%p/n",(void*)mask[padded-len],
  483. //*reinterpret_cast<void**>(data+padded-4));
  484. *reinterpret_cast<uint32_t*>(data+padded-4)&=mask[padded-len];
  485. }
  486. finishWrite(padded);
  487. returndata;
  488. }
  489. status_terr=growData(padded);
  490. if(err==NO_ERROR)gotorestart_write;
  491. returnNULL;
  492. }
  493. status_tParcel::writeInt32(int32_tval)
  494. {
  495. returnwriteAligned(val);
  496. }
  497. status_tParcel::writeInt64(int64_tval)
  498. {
  499. returnwriteAligned(val);
  500. }
  501. status_tParcel::writeFloat(floatval)
  502. {
  503. returnwriteAligned(val);
  504. }
  505. status_tParcel::writeDouble(doubleval)
  506. {
  507. returnwriteAligned(val);
  508. }
  509. status_tParcel::writeIntPtr(intptr_tval)
  510. {
  511. returnwriteAligned(val);
  512. }
  513. status_tParcel::writeCString(constchar*str)
  514. {
  515. returnwrite(str,strlen(str)+1);
  516. }
  517. status_tParcel::writeString8(constString8&str)
  518. {
  519. status_terr=writeInt32(str.bytes());
  520. if(err==NO_ERROR){
  521. err=write(str.string(),str.bytes()+1);
  522. }
  523. returnerr;
  524. }
  525. status_tParcel::writeString16(constString16&str)
  526. {
  527. returnwriteString16(str.string(),str.size());
  528. }
  529. status_tParcel::writeString16(constchar16_t*str,size_tlen)
  530. {
  531. if(str==NULL)returnwriteInt32(-1);
  532. status_terr=writeInt32(len);
  533. if(err==NO_ERROR){
  534. len*=sizeof(char16_t);
  535. uint8_t*data=(uint8_t*)writeInplace(len+sizeof(char16_t));
  536. if(data){
  537. memcpy(data,str,len);
  538. *reinterpret_cast<char16_t*>(data+len)=0;
  539. returnNO_ERROR;
  540. }
  541. err=mError;
  542. }
  543. returnerr;
  544. }
  545. status_tParcel::writeStrongBinder(constsp<IBinder>&val)
  546. {
  547. returnflatten_binder(ProcessState::self(),val,this);
  548. }
  549. status_tParcel::writeWeakBinder(constwp<IBinder>&val)
  550. {
  551. returnflatten_binder(ProcessState::self(),val,this);
  552. }
  553. status_tParcel::writeNativeHandle(constnative_handle*handle)
  554. {
  555. if(!handle||handle->version!=sizeof(native_handle))
  556. returnBAD_TYPE;
  557. status_terr;
  558. err=writeInt32(handle->numFds);
  559. if(err!=NO_ERROR)returnerr;
  560. err=writeInt32(handle->numInts);
  561. if(err!=NO_ERROR)returnerr;
  562. for(inti=0;err==NO_ERROR&&i<handle->numFds;i++)
  563. err=writeDupFileDescriptor(handle->data[i]);
  564. if(err!=NO_ERROR){
  565. LOGD("writenativehandle,writedupfdfailed");
  566. returnerr;
  567. }
  568. err=write(handle->data+handle->numFds,sizeof(int)*handle->numInts);
  569. returnerr;
  570. }
  571. status_tParcel::writeFileDescriptor(intfd)
  572. {
  573. flat_binder_objectobj;
  574. obj.type=BINDER_TYPE_FD;
  575. obj.flags=0x7f|FLAT_BINDER_FLAG_ACCEPTS_FDS;
  576. obj.handle=fd;
  577. obj.cookie=(void*)0;
  578. returnwriteObject(obj,true);
  579. }
  580. status_tParcel::writeDupFileDescriptor(intfd)
  581. {
  582. flat_binder_objectobj;
  583. obj.type=BINDER_TYPE_FD;
  584. obj.flags=0x7f|FLAT_BINDER_FLAG_ACCEPTS_FDS;
  585. obj.handle=dup(fd);
  586. obj.cookie=(void*)1;
  587. returnwriteObject(obj,true);
  588. }
  589. status_tParcel::write(constFlattenable&val)
  590. {
  591. status_terr;
  592. //sizeifneeded
  593. size_tlen=val.getFlattenedSize();
  594. size_tfd_count=val.getFdCount();
  595. err=this->writeInt32(len);
  596. if(err)returnerr;
  597. err=this->writeInt32(fd_count);
  598. if(err)returnerr;
  599. //payload
  600. void*buf=this->writeInplace(PAD_SIZE(len));
  601. if(buf==NULL)
  602. returnBAD_VALUE;
  603. int*fds=NULL;
  604. if(fd_count){
  605. fds=newint[fd_count];
  606. }
  607. err=val.flatten(buf,len,fds,fd_count);
  608. for(size_ti=0;i<fd_count&&err==NO_ERROR;i++){
  609. err=this->writeDupFileDescriptor(fds[i]);
  610. }
  611. if(fd_count){
  612. delete[]fds;
  613. }
  614. returnerr;
  615. }
  616. status_tParcel::writeObject(constflat_binder_object&val,boolnullMetaData)
  617. {
  618. constboolenoughData=(mDataPos+sizeof(val))<=mDataCapacity;
  619. constboolenoughObjects=mObjectsSize<mObjectsCapacity;
  620. if(enoughData&&enoughObjects){
  621. restart_write:
  622. *reinterpret_cast<flat_binder_object*>(mData+mDataPos)=val;
  623. //Needtowritemeta-data?
  624. if(nullMetaData||val.binder!=NULL){
  625. mObjects[mObjectsSize]=mDataPos;
  626. acquire_object(ProcessState::self(),val,this);
  627. mObjectsSize++;
  628. }
  629. //rememberifit'safiledescriptor
  630. if(val.type==BINDER_TYPE_FD){
  631. mHasFds=mFdsKnown=true;
  632. }
  633. returnfinishWrite(sizeof(flat_binder_object));
  634. }
  635. if(!enoughData){
  636. conststatus_terr=growData(sizeof(val));
  637. if(err!=NO_ERROR)returnerr;
  638. }
  639. if(!enoughObjects){
  640. size_tnewSize=((mObjectsSize+2)*3)/2;
  641. size_t*objects=(size_t*)realloc(mObjects,newSize*sizeof(size_t));
  642. if(objects==NULL)returnNO_MEMORY;
  643. mObjects=objects;
  644. mObjectsCapacity=newSize;
  645. }
  646. gotorestart_write;
  647. }
  648. voidParcel::remove(size_tstart,size_tamt)
  649. {
  650. LOG_ALWAYS_FATAL("Parcel::remove()notyetimplemented!");
  651. }
  652. status_tParcel::read(void*outData,size_tlen)const
  653. {
  654. if((mDataPos+PAD_SIZE(len))>=mDataPos&&(mDataPos+PAD_SIZE(len))<=mDataSize){
  655. memcpy(outData,mData+mDataPos,len);
  656. mDataPos+=PAD_SIZE(len);
  657. LOGV("readSettingdataposof%pto%d/n",this,mDataPos);
  658. returnNO_ERROR;
  659. }
  660. returnNOT_ENOUGH_DATA;
  661. }
  662. constvoid*Parcel::readInplace(size_tlen)const
  663. {
  664. if((mDataPos+PAD_SIZE(len))>=mDataPos&&(mDataPos+PAD_SIZE(len))<=mDataSize){
  665. constvoid*data=mData+mDataPos;
  666. mDataPos+=PAD_SIZE(len);
  667. LOGV("readInplaceSettingdataposof%pto%d/n",this,mDataPos);
  668. returndata;
  669. }
  670. returnNULL;
  671. }
  672. template<classT>
  673. status_tParcel::readAligned(T*pArg)const{
  674. COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T))==sizeof(T));
  675. if((mDataPos+sizeof(T))<=mDataSize){
  676. constvoid*data=mData+mDataPos;
  677. mDataPos+=sizeof(T);
  678. *pArg=*reinterpret_cast<constT*>(data);
  679. returnNO_ERROR;
  680. }else{
  681. returnNOT_ENOUGH_DATA;
  682. }
  683. }
  684. template<classT>
  685. TParcel::readAligned()const{
  686. Tresult;
  687. if(readAligned(&result)!=NO_ERROR){
  688. result=0;
  689. }
  690. returnresult;
  691. }
  692. template<classT>
  693. status_tParcel::writeAligned(Tval){
  694. COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T))==sizeof(T));
  695. if((mDataPos+sizeof(val))<=mDataCapacity){
  696. restart_write:
  697. *reinterpret_cast<T*>(mData+mDataPos)=val;
  698. returnfinishWrite(sizeof(val));
  699. }
  700. status_terr=growData(sizeof(val));
  701. if(err==NO_ERROR)gotorestart_write;
  702. returnerr;
  703. }
  704. status_tParcel::readInt32(int32_t*pArg)const
  705. {
  706. returnreadAligned(pArg);
  707. }
  708. int32_tParcel::readInt32()const
  709. {
  710. returnreadAligned<int32_t>();
  711. }
  712. status_tParcel::readInt64(int64_t*pArg)const
  713. {
  714. returnreadAligned(pArg);
  715. }
  716. int64_tParcel::readInt64()const
  717. {
  718. returnreadAligned<int64_t>();
  719. }
  720. status_tParcel::readFloat(float*pArg)const
  721. {
  722. returnreadAligned(pArg);
  723. }
  724. floatParcel::readFloat()const
  725. {
  726. returnreadAligned<float>();
  727. }
  728. status_tParcel::readDouble(double*pArg)const
  729. {
  730. returnreadAligned(pArg);
  731. }
  732. doubleParcel::readDouble()const
  733. {
  734. returnreadAligned<double>();
  735. }
  736. status_tParcel::readIntPtr(intptr_t*pArg)const
  737. {
  738. returnreadAligned(pArg);
  739. }
  740. intptr_tParcel::readIntPtr()const
  741. {
  742. returnreadAligned<intptr_t>();
  743. }
  744. constchar*Parcel::readCString()const
  745. {
  746. constsize_tavail=mDataSize-mDataPos;
  747. if(avail>0){
  748. constchar*str=reinterpret_cast<constchar*>(mData+mDataPos);
  749. //isthestring'strailingNULwithintheparcel'svalidbounds?
  750. constchar*eos=reinterpret_cast<constchar*>(memchr(str,0,avail));
  751. if(eos){
  752. constsize_tlen=eos-str;
  753. mDataPos+=PAD_SIZE(len+1);
  754. LOGV("readCStringSettingdataposof%pto%d/n",this,mDataPos);
  755. returnstr;
  756. }
  757. }
  758. returnNULL;
  759. }
  760. String8Parcel::readString8()const
  761. {
  762. int32_tsize=readInt32();
  763. //watchforpotentialintoverflowadding1fortrailingNUL
  764. if(size>0&&size<INT32_MAX){
  765. constchar*str=(constchar*)readInplace(size+1);
  766. if(str)returnString8(str,size);
  767. }
  768. returnString8();
  769. }
  770. String16Parcel::readString16()const
  771. {
  772. size_tlen;
  773. constchar16_t*str=readString16Inplace(&len);
  774. if(str)returnString16(str,len);
  775. LOGE("ReadingaNULLstringnotsupportedhere.");
  776. returnString16();
  777. }
  778. constchar16_t*Parcel::readString16Inplace(size_t*outLen)const
  779. {
  780. int32_tsize=readInt32();
  781. //watchforpotentialintoverflowfromsize+1
  782. if(size>=0&&size<INT32_MAX){
  783. *outLen=size;
  784. constchar16_t*str=(constchar16_t*)readInplace((size+1)*sizeof(char16_t));
  785. if(str!=NULL){
  786. returnstr;
  787. }
  788. }
  789. *outLen=0;
  790. returnNULL;
  791. }
  792. sp<IBinder>Parcel::readStrongBinder()const
  793. {
  794. sp<IBinder>val;
  795. unflatten_binder(ProcessState::self(),*this,&val);
  796. returnval;
  797. }
  798. wp<IBinder>Parcel::readWeakBinder()const
  799. {
  800. wp<IBinder>val;
  801. unflatten_binder(ProcessState::self(),*this,&val);
  802. returnval;
  803. }
  804. native_handle*Parcel::readNativeHandle()const
  805. {
  806. intnumFds,numInts;
  807. status_terr;
  808. err=readInt32(&numFds);
  809. if(err!=NO_ERROR)return0;
  810. err=readInt32(&numInts);
  811. if(err!=NO_ERROR)return0;
  812. native_handle*h=native_handle_create(numFds,numInts);
  813. for(inti=0;err==NO_ERROR&&i<numFds;i++){
  814. h->data[i]=dup(readFileDescriptor());
  815. if(h->data[i]<0)err=BAD_VALUE;
  816. }
  817. err=read(h->data+numFds,sizeof(int)*numInts);
  818. if(err!=NO_ERROR){
  819. native_handle_close(h);
  820. native_handle_delete(h);
  821. h=0;
  822. }
  823. returnh;
  824. }
  825. intParcel::readFileDescriptor()const
  826. {
  827. constflat_binder_object*flat=readObject(true);
  828. if(flat){
  829. switch(flat->type){
  830. caseBINDER_TYPE_FD:
  831. //LOGI("Returningfiledescriptor%ldfromparcel%p/n",flat->handle,this);
  832. returnflat->handle;
  833. }
  834. }
  835. returnBAD_TYPE;
  836. }
  837. status_tParcel::read(Flattenable&val)const
  838. {
  839. //size
  840. constsize_tlen=this->readInt32();
  841. constsize_tfd_count=this->readInt32();
  842. //payload
  843. voidconst*buf=this->readInplace(PAD_SIZE(len));
  844. if(buf==NULL)
  845. returnBAD_VALUE;
  846. int*fds=NULL;
  847. if(fd_count){
  848. fds=newint[fd_count];
  849. }
  850. status_terr=NO_ERROR;
  851. for(size_ti=0;i<fd_count&&err==NO_ERROR;i++){
  852. fds[i]=dup(this->readFileDescriptor());
  853. if(fds[i]<0)err=BAD_VALUE;
  854. }
  855. if(err==NO_ERROR){
  856. err=val.unflatten(buf,len,fds,fd_count);
  857. }
  858. if(fd_count){
  859. delete[]fds;
  860. }
  861. returnerr;
  862. }
  863. constflat_binder_object*Parcel::readObject(boolnullMetaData)const
  864. {
  865. constsize_tDPOS=mDataPos;
  866. if((DPOS+sizeof(flat_binder_object))<=mDataSize){
  867. constflat_binder_object*obj
  868. =reinterpret_cast<constflat_binder_object*>(mData+DPOS);
  869. mDataPos=DPOS+sizeof(flat_binder_object);
  870. if(!nullMetaData&&(obj->cookie==NULL&&obj->binder==NULL)){
  871. //WhentransferringaNULLobject,wedon'twriteitinto
  872. //theobjectlist,sowedon'twanttocheckforitwhen
  873. //reading.
  874. LOGV("readObjectSettingdataposof%pto%d/n",this,mDataPos);
  875. returnobj;
  876. }
  877. //Ensurethatthisobjectisvalid...
  878. size_t*constOBJS=mObjects;
  879. constsize_tN=mObjectsSize;
  880. size_topos=mNextObjectHint;
  881. if(N>0){
  882. LOGV("Parcel%plookingforobjat%d,hint=%d/n",
  883. this,DPOS,opos);
  884. //Startatthecurrenthintposition,lookingforanobjectat
  885. //thecurrentdataposition.
  886. if(opos<N){
  887. while(opos<(N-1)&&OBJS[opos]<DPOS){
  888. opos++;
  889. }
  890. }else{
  891. opos=N-1;
  892. }
  893. if(OBJS[opos]==DPOS){
  894. //Foundit!
  895. LOGV("Parcelfoundobj%datindex%dwithforwardsearch",
  896. this,DPOS,opos);
  897. mNextObjectHint=opos+1;
  898. LOGV("readObjectSettingdataposof%pto%d/n",this,mDataPos);
  899. returnobj;
  900. }
  901. //Lookbackwardsforit...
  902. while(opos>0&&OBJS[opos]>DPOS){
  903. opos--;
  904. }
  905. if(OBJS[opos]==DPOS){
  906. //Foundit!
  907. LOGV("Parcelfoundobj%datindex%dwithbackwardsearch",
  908. this,DPOS,opos);
  909. mNextObjectHint=opos+1;
  910. LOGV("readObjectSettingdataposof%pto%d/n",this,mDataPos);
  911. returnobj;
  912. }
  913. }
  914. LOGW("AttempttoreadobjectfromParcel%patoffset%dthatisnotintheobjectlist",
  915. this,DPOS);
  916. }
  917. returnNULL;
  918. }
  919. voidParcel::closeFileDescriptors()
  920. {
  921. size_ti=mObjectsSize;
  922. if(i>0){
  923. //LOGI("Closingfiledescriptorsfor%dobjects...",mObjectsSize);
  924. }
  925. while(i>0){
  926. i--;
  927. constflat_binder_object*flat
  928. =reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
  929. if(flat->type==BINDER_TYPE_FD){
  930. //LOGI("Closingfd:%ld/n",flat->handle);
  931. close(flat->handle);
  932. }
  933. }
  934. }
  935. constuint8_t*Parcel::ipcData()const
  936. {
  937. returnmData;
  938. }
  939. size_tParcel::ipcDataSize()const
  940. {
  941. return(mDataSize>mDataPos?mDataSize:mDataPos);
  942. }
  943. constsize_t*Parcel::ipcObjects()const
  944. {
  945. returnmObjects;
  946. }
  947. size_tParcel::ipcObjectsCount()const
  948. {
  949. returnmObjectsSize;
  950. }
  951. voidParcel::ipcSetDataReference(constuint8_t*data,size_tdataSize,
  952. constsize_t*objects,size_tobjectsCount,release_funcrelFunc,void*relCookie)
  953. {
  954. freeDataNoInit();
  955. mError=NO_ERROR;
  956. mData=const_cast<uint8_t*>(data);
  957. mDataSize=mDataCapacity=dataSize;
  958. //LOGI("setDataReferenceSettingdatasizeof%pto%lu(pid=%d)/n",this,mDataSize,getpid());
  959. mDataPos=0;
  960. LOGV("setDataReferenceSettingdataposof%pto%d/n",this,mDataPos);
  961. mObjects=const_cast<size_t*>(objects);
  962. mObjectsSize=mObjectsCapacity=objectsCount;
  963. mNextObjectHint=0;
  964. mOwner=relFunc;
  965. mOwnerCookie=relCookie;
  966. scanForFds();
  967. }
  968. voidParcel::print(TextOutput&to,uint32_tflags)const
  969. {
  970. to<<"Parcel(";
  971. if(errorCheck()!=NO_ERROR){
  972. conststatus_terr=errorCheck();
  973. to<<"Error:"<<(void*)err<<"/""<<strerror(-err)<<"/"";
  974. }elseif(dataSize()>0){
  975. constuint8_t*DATA=data();
  976. to<<indent<<HexDump(DATA,dataSize())<<dedent;
  977. constsize_t*OBJS=objects();
  978. constsize_tN=objectsCount();
  979. for(size_ti=0;i<N;i++){
  980. constflat_binder_object*flat
  981. =reinterpret_cast<constflat_binder_object*>(DATA+OBJS[i]);
  982. to<<endl<<"Object#"<<i<<"@"<<(void*)OBJS[i]<<":"
  983. <<TypeCode(flat->type&0x7f7f7f00)
  984. <<"="<<flat->binder;
  985. }
  986. }else{
  987. to<<"NULL";
  988. }
  989. to<<")";
  990. }
  991. voidParcel::releaseObjects()
  992. {
  993. constsp<ProcessState>proc(ProcessState::self());
  994. size_ti=mObjectsSize;
  995. uint8_t*constdata=mData;
  996. size_t*constobjects=mObjects;
  997. while(i>0){
  998. i--;
  999. constflat_binder_object*flat
  1000. =reinterpret_cast<flat_binder_object*>(data+objects[i]);
  1001. release_object(proc,*flat,this);
  1002. }
  1003. }
  1004. voidParcel::acquireObjects()
  1005. {
  1006. constsp<ProcessState>proc(ProcessState::self());
  1007. size_ti=mObjectsSize;
  1008. uint8_t*constdata=mData;
  1009. size_t*constobjects=mObjects;
  1010. while(i>0){
  1011. i--;
  1012. constflat_binder_object*flat
  1013. =reinterpret_cast<flat_binder_object*>(data+objects[i]);
  1014. acquire_object(proc,*flat,this);
  1015. }
  1016. }
  1017. voidParcel::freeData()
  1018. {
  1019. freeDataNoInit();
  1020. initState();
  1021. }
  1022. voidParcel::freeDataNoInit()
  1023. {
  1024. if(mOwner){
  1025. //LOGI("Freeingdatarefof%p(pid=%d)/n",this,getpid());
  1026. mOwner(this,mData,mDataSize,mObjects,mObjectsSize,mOwnerCookie);
  1027. }else{
  1028. releaseObjects();
  1029. if(mData)free(mData);
  1030. if(mObjects)free(mObjects);
  1031. }
  1032. }
  1033. status_tParcel::growData(size_tlen)
  1034. {
  1035. size_tnewSize=((mDataSize+len)*3)/2;
  1036. return(newSize<=mDataSize)
  1037. ?(status_t)NO_MEMORY
  1038. :continueWrite(newSize);
  1039. }
  1040. status_tParcel::restartWrite(size_tdesired)
  1041. {
  1042. if(mOwner){
  1043. freeData();
  1044. returncontinueWrite(desired);
  1045. }
  1046. uint8_t*data=(uint8_t*)realloc(mData,desired);
  1047. if(!data&&desired>mDataCapacity){
  1048. mError=NO_MEMORY;
  1049. returnNO_MEMORY;
  1050. }
  1051. releaseObjects();
  1052. if(data){
  1053. mData=data;
  1054. mDataCapacity=desired;
  1055. }
  1056. mDataSize=mDataPos=0;
  1057. LOGV("restartWriteSettingdatasizeof%pto%d/n",this,mDataSize);
  1058. LOGV("restartWriteSettingdataposof%pto%d/n",this,mDataPos);
  1059. free(mObjects);
  1060. mObjects=NULL;
  1061. mObjectsSize=mObjectsCapacity=0;
  1062. mNextObjectHint=0;
  1063. mHasFds=false;
  1064. mFdsKnown=true;
  1065. returnNO_ERROR;
  1066. }
  1067. status_tParcel::continueWrite(size_tdesired)
  1068. {
  1069. //Ifshrinking,firstadjustforanyobjectsthatappear
  1070. //afterthenewdatasize.
  1071. size_tobjectsSize=mObjectsSize;
  1072. if(desired<mDataSize){
  1073. if(desired==0){
  1074. objectsSize=0;
  1075. }else{
  1076. while(objectsSize>0){
  1077. if(mObjects[objectsSize-1]<desired)
  1078. break;
  1079. objectsSize--;
  1080. }
  1081. }
  1082. }
  1083. if(mOwner){
  1084. //Ifthesizeisgoingtozero,justreleasetheowner'sdata.
  1085. if(desired==0){
  1086. freeData();
  1087. returnNO_ERROR;
  1088. }
  1089. //Ifthereisadifferentowner,weneedtotake
  1090. //posession.
  1091. uint8_t*data=(uint8_t*)malloc(desired);
  1092. if(!data){
  1093. mError=NO_MEMORY;
  1094. returnNO_MEMORY;
  1095. }
  1096. size_t*objects=NULL;
  1097. if(objectsSize){
  1098. objects=(size_t*)malloc(objectsSize*sizeof(size_t));
  1099. if(!objects){
  1100. mError=NO_MEMORY;
  1101. returnNO_MEMORY;
  1102. }
  1103. //Littlehacktoonlyacquirereferencesonobjects
  1104. //wewillbekeeping.
  1105. size_toldObjectsSize=mObjectsSize;
  1106. mObjectsSize=objectsSize;
  1107. acquireObjects();
  1108. mObjectsSize=oldObjectsSize;
  1109. }
  1110. if(mData){
  1111. memcpy(data,mData,mDataSize<desired?mDataSize:desired);
  1112. }
  1113. if(objects&&mObjects){
  1114. memcpy(objects,mObjects,objectsSize*sizeof(size_t));
  1115. }
  1116. //LOGI("Freeingdatarefof%p(pid=%d)/n",this,getpid());
  1117. mOwner(this,mData,mDataSize,mObjects,mObjectsSize,mOwnerCookie);
  1118. mOwner=NULL;
  1119. mData=data;
  1120. mObjects=objects;
  1121. mDataSize=(mDataSize<desired)?mDataSize:desired;
  1122. LOGV("continueWriteSettingdatasizeof%pto%d/n",this,mDataSize);
  1123. mDataCapacity=desired;
  1124. mObjectsSize=mObjectsCapacity=objectsSize;
  1125. mNextObjectHint=0;
  1126. }elseif(mData){
  1127. if(objectsSize<mObjectsSize){
  1128. //Needtoreleaserefsonanyobjectswearedropping.
  1129. constsp<ProcessState>proc(ProcessState::self());
  1130. for(size_ti=objectsSize;i<mObjectsSize;i++){
  1131. constflat_binder_object*flat
  1132. =reinterpret_cast<flat_binder_object*>(mData+mObjects[i]);
  1133. if(flat->type==BINDER_TYPE_FD){
  1134. //willneedtorescanbecausewemayhaveloppedofftheonlyFDs
  1135. mFdsKnown=false;
  1136. }
  1137. release_object(proc,*flat,this);
  1138. }
  1139. size_t*objects=
  1140. (size_t*)realloc(mObjects,objectsSize*sizeof(size_t));
  1141. if(objects){
  1142. mObjects=objects;
  1143. }
  1144. mObjectsSize=objectsSize;
  1145. mNextObjectHint=0;
  1146. }
  1147. //Weownthedata,sowecanjustdoarealloc().
  1148. if(desired>mDataCapacity){
  1149. uint8_t*data=(uint8_t*)realloc(mData,desired);
  1150. if(data){
  1151. mData=data;
  1152. mDataCapacity=desired;
  1153. }elseif(desired>mDataCapacity){
  1154. mError=NO_MEMORY;
  1155. returnNO_MEMORY;
  1156. }
  1157. }else{
  1158. mDataSize=desired;
  1159. LOGV("continueWriteSettingdatasizeof%pto%d/n",this,mDataSize);
  1160. if(mDataPos>desired){
  1161. mDataPos=desired;
  1162. LOGV("continueWriteSettingdataposof%pto%d/n",this,mDataPos);
  1163. }
  1164. }
  1165. }else{
  1166. //Thisisthefirstdata.Easy!
  1167. uint8_t*data=(uint8_t*)malloc(desired);
  1168. if(!data){
  1169. mError=NO_MEMORY;
  1170. returnNO_MEMORY;
  1171. }
  1172. if(!(mDataCapacity==0&&mObjects==NULL
  1173. &&mObjectsCapacity==0)){
  1174. LOGE("continueWrite:%d/%p/%d/%d",mDataCapacity,mObjects,mObjectsCapacity,desired);
  1175. }
  1176. mData=data;
  1177. mDataSize=mDataPos=0;
  1178. LOGV("continueWriteSettingdatasizeof%pto%d/n",this,mDataSize);
  1179. LOGV("continueWriteSettingdataposof%pto%d/n",this,mDataPos);
  1180. mDataCapacity=desired;
  1181. }
  1182. returnNO_ERROR;
  1183. }
  1184. voidParcel::initState()
  1185. {
  1186. mError=NO_ERROR;
  1187. mData=0;
  1188. mDataSize=0;
  1189. mDataCapacity=0;
  1190. mDataPos=0;
  1191. LOGV("initStateSettingdatasizeof%pto%d/n",this,mDataSize);
  1192. LOGV("initStateSettingdataposof%pto%d/n",this,mDataPos);
  1193. mObjects=NULL;
  1194. mObjectsSize=0;
  1195. mObjectsCapacity=0;
  1196. mNextObjectHint=0;
  1197. mHasFds=false;
  1198. mFdsKnown=true;
  1199. mOwner=NULL;
  1200. }
  1201. voidParcel::scanForFds()const
  1202. {
  1203. boolhasFds=false;
  1204. for(size_ti=0;i<mObjectsSize;i++){
  1205. constflat_binder_object*flat
  1206. =reinterpret_cast<constflat_binder_object*>(mData+mObjects[i]);
  1207. if(flat->type==BINDER_TYPE_FD){
  1208. hasFds=true;
  1209. break;
  1210. }
  1211. }
  1212. mHasFds=hasFds;
  1213. mFdsKnown=true;
  1214. }
  1215. };//namespaceandroid
/* * 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 <binder/Parcel.h>#include <binder/Binder.h>#include <binder/BpBinder.h>#include <utils/Debug.h>#include <binder/ProcessState.h>#include <utils/Log.h>#include <utils/String8.h>#include <utils/String16.h>#include <utils/TextOutput.h>#include <utils/misc.h>#include <utils/Flattenable.h>#include <private/binder/binder_module.h>#include <stdio.h>#include <stdlib.h>#include <stdint.h>#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<ProcessState>& 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<IBinder*>(obj.cookie)->incStrong(who); } return; case BINDER_TYPE_WEAK_BINDER: if (obj.binder) static_cast<RefBase::weakref_type*>(obj.binder)->incWeak(who); return; case BINDER_TYPE_HANDLE: { const sp<IBinder> 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<IBinder> 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<ProcessState>& 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<IBinder*>(obj.cookie)->decStrong(who); } return; case BINDER_TYPE_WEAK_BINDER: if (obj.binder) static_cast<RefBase::weakref_type*>(obj.binder)->decWeak(who); return; case BINDER_TYPE_HANDLE: { const sp<IBinder> 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<IBinder> 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<IBinder>& binder, const flat_binder_object& flat, Parcel* out){ return out->writeObject(flat, false);}status_t flatten_binder(const sp<ProcessState>& proc, const sp<IBinder>& 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<ProcessState>& proc, const wp<IBinder>& binder, Parcel* out){ flat_binder_object obj; obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS; if (binder != NULL) { sp<IBinder> 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); } // 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<ProcessState>& proc, const Parcel& in, sp<IBinder>* out){ const flat_binder_object* flat = in.readObject(false); if (flat) { switch (flat->type) { case BINDER_TYPE_BINDER: *out = static_cast<IBinder*>(flat->cookie); return finish_unflatten_binder(NULL, *flat, in); case BINDER_TYPE_HANDLE: *out = proc->getStrongProxyForHandle(flat->handle); return finish_unflatten_binder( static_cast<BpBinder*>(out->get()), *flat, in); } } return BAD_TYPE;}status_t unflatten_binder(const sp<ProcessState>& proc, const Parcel& in, wp<IBinder>* out){ const flat_binder_object* flat = in.readObject(false); if (flat) { switch (flat->type) { case BINDER_TYPE_BINDER: *out = static_cast<IBinder*>(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<IBinder*>(flat->cookie), static_cast<RefBase::weakref_type*>(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<BpBinder*>(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<uint8_t*>(data()), buffer, len); mDataSize = len; mFdsKnown = false; } return err;}status_t Parcel::appendFrom(Parcel *parcel, size_t offset, size_t len){ const sp<ProcessState> 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; } // 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<flat_binder_object*>(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<void**>(data+padded-4)); *reinterpret_cast<uint32_t*>(data+padded-4) &= mask[padded-len]; } 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<char16_t*>(data+len) = 0; return NO_ERROR; } err = mError; } return err;}status_t Parcel::writeStrongBinder(const sp<IBinder>& val){ return flatten_binder(ProcessState::self(), val, this);}status_t Parcel::writeWeakBinder(const wp<IBinder>& 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 && i<handle->numFds ; 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<fd_count && err==NO_ERROR ; 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<flat_binder_object*>(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; } goto restart_write;}void Parcel::remove(size_t start, size_t amt){ LOG_ALWAYS_FATAL("Parcel::remove() not yet implemented!");}status_t Parcel::read(void* outData, size_t len) const{ if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize) { memcpy(outData, mData+mDataPos, len); mDataPos += PAD_SIZE(len); LOGV("read Setting data pos of %p to %d/n", this, mDataPos); return NO_ERROR; } return NOT_ENOUGH_DATA;}const void* Parcel::readInplace(size_t len) const{ if ((mDataPos+PAD_SIZE(len)) >= mDataPos && (mDataPos+PAD_SIZE(len)) <= mDataSize) { const void* data = mData+mDataPos; mDataPos += PAD_SIZE(len); LOGV("readInplace Setting data pos of %p to %d/n", this, mDataPos); return data; } return NULL;}template<class T>status_t Parcel::readAligned(T *pArg) const { COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T)); if ((mDataPos+sizeof(T)) <= mDataSize) { const void* data = mData+mDataPos; mDataPos += sizeof(T); *pArg = *reinterpret_cast<const T*>(data); return NO_ERROR; } else { return NOT_ENOUGH_DATA; }}template<class T>T Parcel::readAligned() const { T result; if (readAligned(&result) != NO_ERROR) { result = 0; } return result;}template<class T>status_t Parcel::writeAligned(T val) { COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T)); if ((mDataPos+sizeof(val)) <= mDataCapacity) {restart_write: *reinterpret_cast<T*>(mData+mDataPos) = val; return finishWrite(sizeof(val)); } status_t err = growData(sizeof(val)); if (err == NO_ERROR) goto restart_write; return err;}status_t Parcel::readInt32(int32_t *pArg) const{ return readAligned(pArg);}int32_t Parcel::readInt32() const{ return readAligned<int32_t>();}status_t Parcel::readInt64(int64_t *pArg) const{ return readAligned(pArg);}int64_t Parcel::readInt64() const{ return readAligned<int64_t>();}status_t Parcel::readFloat(float *pArg) const{ return readAligned(pArg);}float Parcel::readFloat() const{ return readAligned<float>();}status_t Parcel::readDouble(double *pArg) const{ return readAligned(pArg);}double Parcel::readDouble() const{ return readAligned<double>();}status_t Parcel::readIntPtr(intptr_t *pArg) const{ return readAligned(pArg);}intptr_t Parcel::readIntPtr() const{ return readAligned<intptr_t>();}const char* Parcel::readCString() const{ const size_t avail = mDataSize-mDataPos; if (avail > 0) { const char* str = reinterpret_cast<const char*>(mData+mDataPos); // is the string's trailing NUL within the parcel's valid bounds? const char* eos = reinterpret_cast<const char*>(memchr(str, 0, avail)); if (eos) { const size_t len = eos - str; mDataPos += PAD_SIZE(len+1); LOGV("readCString Setting data pos of %p to %d/n", this, mDataPos); return str; } } return NULL;}String8 Parcel::readString8() const{ int32_t size = readInt32(); // watch for potential int overflow adding 1 for trailing NUL if (size > 0 && size < INT32_MAX) { const char* str = (const char*)readInplace(size+1); if (str) return String8(str, size); } return String8();}String16 Parcel::readString16() const{ size_t len; const char16_t* str = readString16Inplace(&len); if (str) return String16(str, len); LOGE("Reading a NULL string not supported here."); return String16();}const char16_t* Parcel::readString16Inplace(size_t* outLen) const{ int32_t size = readInt32(); // watch for potential int overflow from size+1 if (size >= 0 && size < INT32_MAX) { *outLen = size; const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t)); if (str != NULL) { return str; } } *outLen = 0; return NULL;}sp<IBinder> Parcel::readStrongBinder() const{ sp<IBinder> val; unflatten_binder(ProcessState::self(), *this, &val); return val;}wp<IBinder> Parcel::readWeakBinder() const{ wp<IBinder> val; unflatten_binder(ProcessState::self(), *this, &val); return val;}native_handle* Parcel::readNativeHandle() const{ int numFds, numInts; status_t err; err = readInt32(&numFds); if (err != NO_ERROR) return 0; err = readInt32(&numInts); if (err != NO_ERROR) return 0; native_handle* h = native_handle_create(numFds, numInts); for (int i=0 ; err==NO_ERROR && i<numFds ; i++) { h->data[i] = dup(readFileDescriptor()); if (h->data[i] < 0) err = BAD_VALUE; } err = read(h->data + numFds, sizeof(int)*numInts); if (err != NO_ERROR) { native_handle_close(h); native_handle_delete(h); h = 0; } return h;}int Parcel::readFileDescriptor() const{ const flat_binder_object* flat = readObject(true); if (flat) { switch (flat->type) { case BINDER_TYPE_FD: //LOGI("Returning file descriptor %ld from parcel %p/n", flat->handle, this); return flat->handle; } } return BAD_TYPE;}status_t Parcel::read(Flattenable& val) const{ // size const size_t len = this->readInt32(); const size_t fd_count = this->readInt32(); // payload void const* buf = this->readInplace(PAD_SIZE(len)); if (buf == NULL) return BAD_VALUE; int* fds = NULL; if (fd_count) { fds = new int[fd_count]; } status_t err = NO_ERROR; for (size_t i=0 ; i<fd_count && err==NO_ERROR ; i++) { fds[i] = dup(this->readFileDescriptor()); if (fds[i] < 0) err = BAD_VALUE; } if (err == NO_ERROR) { err = val.unflatten(buf, len, fds, fd_count); } if (fd_count) { delete [] fds; } return err;}const flat_binder_object* Parcel::readObject(bool nullMetaData) const{ const size_t DPOS = mDataPos; if ((DPOS+sizeof(flat_binder_object)) <= mDataSize) { const flat_binder_object* obj = reinterpret_cast<const flat_binder_object*>(mData+DPOS); mDataPos = DPOS + sizeof(flat_binder_object); if (!nullMetaData && (obj->cookie == NULL && obj->binder == NULL)) { // When transferring a NULL object, we don't write it into // the object list, so we don't want to check for it when // reading. LOGV("readObject Setting data pos of %p to %d/n", this, mDataPos); return obj; } // Ensure that this object is valid... size_t* const OBJS = mObjects; const size_t N = mObjectsSize; size_t opos = mNextObjectHint; if (N > 0) { LOGV("Parcel %p looking for obj at %d, hint=%d/n", this, DPOS, opos); // Start at the current hint position, looking for an object at // the current data position. if (opos < N) { while (opos < (N-1) && OBJS[opos] < DPOS) { opos++; } } else { opos = N-1; } if (OBJS[opos] == DPOS) { // Found it! LOGV("Parcel found obj %d at index %d with forward search", this, DPOS, opos); mNextObjectHint = opos+1; LOGV("readObject Setting data pos of %p to %d/n", this, mDataPos); return obj; } // Look backwards for it... while (opos > 0 && OBJS[opos] > DPOS) { opos--; } if (OBJS[opos] == DPOS) { // Found it! LOGV("Parcel found obj %d at index %d with backward search", this, DPOS, opos); mNextObjectHint = opos+1; LOGV("readObject Setting data pos of %p to %d/n", this, mDataPos); return obj; } } LOGW("Attempt to read object from Parcel %p at offset %d that is not in the object list", this, DPOS); } return NULL;}void Parcel::closeFileDescriptors(){ size_t i = mObjectsSize; if (i > 0) { //LOGI("Closing file descriptors for %d objects...", mObjectsSize); } while (i > 0) { i--; const flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]); if (flat->type == BINDER_TYPE_FD) { //LOGI("Closing fd: %ld/n", flat->handle); close(flat->handle); } }}const uint8_t* Parcel::ipcData() const{ return mData;}size_t Parcel::ipcDataSize() const{ return (mDataSize > mDataPos ? mDataSize : mDataPos);}const size_t* Parcel::ipcObjects() const{ return mObjects;}size_t Parcel::ipcObjectsCount() const{ return mObjectsSize;}void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize, const size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie){ freeDataNoInit(); mError = NO_ERROR; mData = const_cast<uint8_t*>(data); mDataSize = mDataCapacity = dataSize; //LOGI("setDataReference Setting data size of %p to %lu (pid=%d)/n", this, mDataSize, getpid()); mDataPos = 0; LOGV("setDataReference Setting data pos of %p to %d/n", this, mDataPos); mObjects = const_cast<size_t*>(objects); mObjectsSize = mObjectsCapacity = objectsCount; mNextObjectHint = 0; mOwner = relFunc; mOwnerCookie = relCookie; scanForFds();}void Parcel::print(TextOutput& to, uint32_t flags) const{ to << "Parcel("; if (errorCheck() != NO_ERROR) { const status_t err = errorCheck(); to << "Error: " << (void*)err << " /"" << strerror(-err) << "/""; } else if (dataSize() > 0) { const uint8_t* DATA = data(); to << indent << HexDump(DATA, dataSize()) << dedent; const size_t* OBJS = objects(); const size_t N = objectsCount(); for (size_t i=0; i<N; i++) { const flat_binder_object* flat = reinterpret_cast<const flat_binder_object*>(DATA+OBJS[i]); to << endl << "Object #" << i << " @ " << (void*)OBJS[i] << ": " << TypeCode(flat->type & 0x7f7f7f00) << " = " << flat->binder; } } else { to << "NULL"; } to << ")";}void Parcel::releaseObjects(){ const sp<ProcessState> proc(ProcessState::self()); size_t i = mObjectsSize; uint8_t* const data = mData; size_t* const objects = mObjects; while (i > 0) { i--; const flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(data+objects[i]); release_object(proc, *flat, this); }}void Parcel::acquireObjects(){ const sp<ProcessState> proc(ProcessState::self()); size_t i = mObjectsSize; uint8_t* const data = mData; size_t* const objects = mObjects; while (i > 0) { i--; const flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(data+objects[i]); acquire_object(proc, *flat, this); }}void Parcel::freeData(){ freeDataNoInit(); initState();}void Parcel::freeDataNoInit(){ if (mOwner) { //LOGI("Freeing data ref of %p (pid=%d)/n", this, getpid()); mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie); } else { releaseObjects(); if (mData) free(mData); if (mObjects) free(mObjects); }}status_t Parcel::growData(size_t len){ size_t newSize = ((mDataSize+len)*3)/2; return (newSize <= mDataSize) ? (status_t) NO_MEMORY : continueWrite(newSize);}status_t Parcel::restartWrite(size_t desired){ if (mOwner) { freeData(); return continueWrite(desired); } uint8_t* data = (uint8_t*)realloc(mData, desired); if (!data && desired > mDataCapacity) { mError = NO_MEMORY; return NO_MEMORY; } releaseObjects(); if (data) { mData = data; mDataCapacity = desired; } mDataSize = mDataPos = 0; LOGV("restartWrite Setting data size of %p to %d/n", this, mDataSize); LOGV("restartWrite Setting data pos of %p to %d/n", this, mDataPos); free(mObjects); mObjects = NULL; mObjectsSize = mObjectsCapacity = 0; mNextObjectHint = 0; mHasFds = false; mFdsKnown = true; return NO_ERROR;}status_t Parcel::continueWrite(size_t desired){ // If shrinking, first adjust for any objects that appear // after the new data size. size_t objectsSize = mObjectsSize; if (desired < mDataSize) { if (desired == 0) { objectsSize = 0; } else { while (objectsSize > 0) { if (mObjects[objectsSize-1] < desired) break; objectsSize--; } } } if (mOwner) { // If the size is going to zero, just release the owner's data. if (desired == 0) { freeData(); return NO_ERROR; } // If there is a different owner, we need to take // posession. uint8_t* data = (uint8_t*)malloc(desired); if (!data) { mError = NO_MEMORY; return NO_MEMORY; } size_t* objects = NULL; if (objectsSize) { objects = (size_t*)malloc(objectsSize*sizeof(size_t)); if (!objects) { mError = NO_MEMORY; return NO_MEMORY; } // Little hack to only acquire references on objects // we will be keeping. size_t oldObjectsSize = mObjectsSize; mObjectsSize = objectsSize; acquireObjects(); mObjectsSize = oldObjectsSize; } if (mData) { memcpy(data, mData, mDataSize < desired ? mDataSize : desired); } if (objects && mObjects) { memcpy(objects, mObjects, objectsSize*sizeof(size_t)); } //LOGI("Freeing data ref of %p (pid=%d)/n", this, getpid()); mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie); mOwner = NULL; mData = data; mObjects = objects; mDataSize = (mDataSize < desired) ? mDataSize : desired; LOGV("continueWrite Setting data size of %p to %d/n", this, mDataSize); mDataCapacity = desired; mObjectsSize = mObjectsCapacity = objectsSize; mNextObjectHint = 0; } else if (mData) { if (objectsSize < mObjectsSize) { // Need to release refs on any objects we are dropping. const sp<ProcessState> proc(ProcessState::self()); for (size_t i=objectsSize; i<mObjectsSize; i++) { const flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(mData+mObjects[i]); if (flat->type == BINDER_TYPE_FD) { // will need to rescan because we may have lopped off the only FDs mFdsKnown = false; } release_object(proc, *flat, this); } size_t* objects = (size_t*)realloc(mObjects, objectsSize*sizeof(size_t)); if (objects) { mObjects = objects; } mObjectsSize = objectsSize; mNextObjectHint = 0; } // We own the data, so we can just do a realloc(). if (desired > mDataCapacity) { uint8_t* data = (uint8_t*)realloc(mData, desired); if (data) { mData = data; mDataCapacity = desired; } else if (desired > mDataCapacity) { mError = NO_MEMORY; return NO_MEMORY; } } else { mDataSize = desired; LOGV("continueWrite Setting data size of %p to %d/n", this, mDataSize); if (mDataPos > desired) { mDataPos = desired; LOGV("continueWrite Setting data pos of %p to %d/n", this, mDataPos); } } } else { // This is the first data. Easy! uint8_t* data = (uint8_t*)malloc(desired); if (!data) { mError = NO_MEMORY; return NO_MEMORY; } if(!(mDataCapacity == 0 && mObjects == NULL && mObjectsCapacity == 0)) { LOGE("continueWrite: %d/%p/%d/%d", mDataCapacity, mObjects, mObjectsCapacity, desired); } mData = data; mDataSize = mDataPos = 0; LOGV("continueWrite Setting data size of %p to %d/n", this, mDataSize); LOGV("continueWrite Setting data pos of %p to %d/n", this, mDataPos); mDataCapacity = desired; } return NO_ERROR;}void Parcel::initState(){ mError = NO_ERROR; mData = 0; mDataSize = 0; mDataCapacity = 0; mDataPos = 0; LOGV("initState Setting data size of %p to %d/n", this, mDataSize); LOGV("initState Setting data pos of %p to %d/n", this, mDataPos); mObjects = NULL; mObjectsSize = 0; mObjectsCapacity = 0; mNextObjectHint = 0; mHasFds = false; mFdsKnown = true; mOwner = NULL;}void Parcel::scanForFds() const{ bool hasFds = false; for (size_t i=0; i<mObjectsSize; i++) { const flat_binder_object* flat = reinterpret_cast<const flat_binder_object*>(mData + mObjects[i]); if (flat->type == BINDER_TYPE_FD) { hasFds = true; break; } } mHasFds = hasFds; mFdsKnown = true;}}; // namespace android

本文的源码使用的是Android 2.1版本。

更多相关文章

  1. 【Android】学习笔记(5)——浅谈Handler
  2. Android(安卓)Bitmap图片处理,防止内存溢出
  3. GC机制,你真的了解吗?
  4. Android的消息机制之ThreadLocal的工作原理
  5. Android(安卓)Studio使用profile简单优雅的查看内存变化
  6. Android--关于Cursor空指针的问题
  7. Android事件分发机制学习笔记
  8. 使用Valgrind找出Android中Native程序内存泄露问题
  9. android onPause()和onStop()区别

随机推荐

  1. android toast使用总结
  2. Android(安卓)AsyncTask几个注意事项
  3. Android(安卓)Studio 2.2 NDK开发 opencv
  4. 高逼格UI-ASD(Android(安卓)Support Desi
  5. Android开发:设置圆形Button
  6. android的小细节
  7. android usb相关知识总结
  8. Android数据存储操作
  9. 打开Android(安卓)PVLogger的方法
  10. android的Spinner控件的自定义样式设置以