diff options
Diffstat (limited to 'include/utils')
38 files changed, 539 insertions, 3088 deletions
diff --git a/include/utils/Binder.h b/include/utils/Binder.h deleted file mode 100644 index b5b8d98..0000000 --- a/include/utils/Binder.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2008 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_BINDER_H -#define ANDROID_BINDER_H - -#include <utils/IBinder.h> - -// --------------------------------------------------------------------------- -namespace android { - -class BBinder : public IBinder -{ -public: - BBinder(); - - virtual String16 getInterfaceDescriptor() const; - virtual bool isBinderAlive() const; - virtual status_t pingBinder(); - virtual status_t dump(int fd, const Vector<String16>& args); - - virtual status_t transact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); - - virtual status_t linkToDeath(const sp<DeathRecipient>& recipient, - void* cookie = NULL, - uint32_t flags = 0); - - virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient, - void* cookie = NULL, - uint32_t flags = 0, - wp<DeathRecipient>* outRecipient = NULL); - - virtual void attachObject( const void* objectID, - void* object, - void* cleanupCookie, - object_cleanup_func func); - virtual void* findObject(const void* objectID) const; - virtual void detachObject(const void* objectID); - - virtual BBinder* localBinder(); - -protected: - virtual ~BBinder(); - - virtual status_t onTransact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); - -private: - BBinder(const BBinder& o); - BBinder& operator=(const BBinder& o); - - class Extras; - - Extras* mExtras; - void* mReserved0; -}; - -// --------------------------------------------------------------------------- - -class BpRefBase : public virtual RefBase -{ -protected: - BpRefBase(const sp<IBinder>& o); - virtual ~BpRefBase(); - virtual void onFirstRef(); - virtual void onLastStrongRef(const void* id); - virtual bool onIncStrongAttempted(uint32_t flags, const void* id); - - inline IBinder* remote() { return mRemote; } - inline IBinder* remote() const { return mRemote; } - -private: - BpRefBase(const BpRefBase& o); - BpRefBase& operator=(const BpRefBase& o); - - IBinder* const mRemote; - RefBase::weakref_type* mRefs; - volatile int32_t mState; -}; - -}; // namespace android - -// --------------------------------------------------------------------------- - -#endif // ANDROID_BINDER_H diff --git a/include/utils/BpBinder.h b/include/utils/BpBinder.h deleted file mode 100644 index 7b96e29..0000000 --- a/include/utils/BpBinder.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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_BPBINDER_H -#define ANDROID_BPBINDER_H - -#include <utils/IBinder.h> -#include <utils/KeyedVector.h> -#include <utils/threads.h> - -// --------------------------------------------------------------------------- -namespace android { - -class BpBinder : public IBinder -{ -public: - BpBinder(int32_t handle); - - inline int32_t handle() const { return mHandle; } - - virtual String16 getInterfaceDescriptor() const; - virtual bool isBinderAlive() const; - virtual status_t pingBinder(); - virtual status_t dump(int fd, const Vector<String16>& args); - - virtual status_t transact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); - - virtual status_t linkToDeath(const sp<DeathRecipient>& recipient, - void* cookie = NULL, - uint32_t flags = 0); - virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient, - void* cookie = NULL, - uint32_t flags = 0, - wp<DeathRecipient>* outRecipient = NULL); - - virtual void attachObject( const void* objectID, - void* object, - void* cleanupCookie, - object_cleanup_func func); - virtual void* findObject(const void* objectID) const; - virtual void detachObject(const void* objectID); - - virtual BpBinder* remoteBinder(); - - status_t setConstantData(const void* data, size_t size); - void sendObituary(); - - class ObjectManager - { - public: - ObjectManager(); - ~ObjectManager(); - - void attach( const void* objectID, - void* object, - void* cleanupCookie, - IBinder::object_cleanup_func func); - void* find(const void* objectID) const; - void detach(const void* objectID); - - void kill(); - - private: - ObjectManager(const ObjectManager&); - ObjectManager& operator=(const ObjectManager&); - - struct entry_t - { - void* object; - void* cleanupCookie; - IBinder::object_cleanup_func func; - }; - - KeyedVector<const void*, entry_t> mObjects; - }; - -protected: - virtual ~BpBinder(); - virtual void onFirstRef(); - virtual void onLastStrongRef(const void* id); - virtual bool onIncStrongAttempted(uint32_t flags, const void* id); - -private: - const int32_t mHandle; - - struct Obituary { - wp<DeathRecipient> recipient; - void* cookie; - uint32_t flags; - }; - - void reportOneDeath(const Obituary& obit); - - mutable Mutex mLock; - volatile int32_t mAlive; - volatile int32_t mObitsSent; - Vector<Obituary>* mObituaries; - ObjectManager mObjects; - Parcel* mConstantData; -}; - -}; // namespace android - -// --------------------------------------------------------------------------- - -#endif // ANDROID_BPBINDER_H diff --git a/include/utils/Debug.h b/include/utils/Debug.h index a662b9c..21d04bd 100644 --- a/include/utils/Debug.h +++ b/include/utils/Debug.h @@ -14,10 +14,6 @@ * limitations under the License. */ -// -// Debugging tools. These should be able to be stripped -// in release builds. -// #ifndef ANDROID_DEBUG_H #define ANDROID_DEBUG_H @@ -25,9 +21,30 @@ #include <sys/types.h> namespace android { +// --------------------------------------------------------------------------- +#ifdef __cplusplus template<bool> struct CompileTimeAssert; template<> struct CompileTimeAssert<true> {}; +#define COMPILE_TIME_ASSERT(_exp) \ + template class CompileTimeAssert< (_exp) >; +#endif + +// --------------------------------------------------------------------------- + +#ifdef __cplusplus +template<bool C, typename LSH, typename RHS> struct CompileTimeIfElse; +template<typename LHS, typename RHS> +struct CompileTimeIfElse<true, LHS, RHS> { typedef LHS TYPE; }; +template<typename LHS, typename RHS> +struct CompileTimeIfElse<false, LHS, RHS> { typedef RHS TYPE; }; +#endif + +// --------------------------------------------------------------------------- + +#ifdef __cplusplus +extern "C" { +#endif const char* stringForIndent(int32_t indentLevel); @@ -35,11 +52,17 @@ typedef void (*debugPrintFunc)(void* cookie, const char* txt); void printTypeCode(uint32_t typeCode, debugPrintFunc func = 0, void* cookie = 0); + void printHexData(int32_t indent, const void *buf, size_t length, size_t bytesPerLine=16, int32_t singleLineBytesCutoff=16, size_t alignment=0, bool cArrayStyle=false, debugPrintFunc func = 0, void* cookie = 0); +#ifdef __cplusplus +} +#endif + +// --------------------------------------------------------------------------- }; // namespace android #endif // ANDROID_DEBUG_H diff --git a/include/utils/IBinder.h b/include/utils/IBinder.h deleted file mode 100644 index 7370330..0000000 --- a/include/utils/IBinder.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 2008 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_IBINDER_H -#define ANDROID_IBINDER_H - -#include <utils/Errors.h> -#include <utils/RefBase.h> -#include <utils/String16.h> -#include <utils/Vector.h> - - -#define B_PACK_CHARS(c1, c2, c3, c4) \ - ((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4)) - -// --------------------------------------------------------------------------- -namespace android { - -class BBinder; -class BpBinder; -class IInterface; -class Parcel; - -/** - * Base class and low-level protocol for a remotable object. - * You can derive from this class to create an object for which other - * processes can hold references to it. Communication between processes - * (method calls, property get and set) is down through a low-level - * protocol implemented on top of the transact() API. - */ -class IBinder : public virtual RefBase -{ -public: - enum { - FIRST_CALL_TRANSACTION = 0x00000001, - LAST_CALL_TRANSACTION = 0x00ffffff, - - PING_TRANSACTION = B_PACK_CHARS('_','P','N','G'), - DUMP_TRANSACTION = B_PACK_CHARS('_','D','M','P'), - INTERFACE_TRANSACTION = B_PACK_CHARS('_', 'N', 'T', 'F'), - - // Corresponds to tfOneWay -- an asynchronous call. - FLAG_ONEWAY = 0x00000001 - }; - - inline IBinder() { } - - /** - * Check if this IBinder implements the interface named by - * @a descriptor. If it does, the base pointer to it is returned, - * which you can safely static_cast<> to the concrete C++ interface. - */ - virtual sp<IInterface> queryLocalInterface(const String16& descriptor); - - /** - * Return the canonical name of the interface provided by this IBinder - * object. - */ - virtual String16 getInterfaceDescriptor() const = 0; - - virtual bool isBinderAlive() const = 0; - virtual status_t pingBinder() = 0; - virtual status_t dump(int fd, const Vector<String16>& args) = 0; - - virtual status_t transact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0) = 0; - - /** - * This method allows you to add data that is transported through - * IPC along with your IBinder pointer. When implementing a Binder - * object, override it to write your desired data in to @a outData. - * You can then call getConstantData() on your IBinder to retrieve - * that data, from any process. You MUST return the number of bytes - * written in to the parcel (including padding). - */ - class DeathRecipient : public virtual RefBase - { - public: - virtual void binderDied(const wp<IBinder>& who) = 0; - }; - - /** - * Register the @a recipient for a notification if this binder - * goes away. If this binder object unexpectedly goes away - * (typically because its hosting process has been killed), - * then DeathRecipient::binderDied() will be called with a referene - * to this. - * - * The @a cookie is optional -- if non-NULL, it should be a - * memory address that you own (that is, you know it is unique). - * - * @note You will only receive death notifications for remote binders, - * as local binders by definition can't die without you dying as well. - * Trying to use this function on a local binder will result in an - * INVALID_OPERATION code being returned and nothing happening. - * - * @note This link always holds a weak reference to its recipient. - * - * @note You will only receive a weak reference to the dead - * binder. You should not try to promote this to a strong reference. - * (Nor should you need to, as there is nothing useful you can - * directly do with it now that it has passed on.) - */ - virtual status_t linkToDeath(const sp<DeathRecipient>& recipient, - void* cookie = NULL, - uint32_t flags = 0) = 0; - - /** - * Remove a previously registered death notification. - * The @a recipient will no longer be called if this object - * dies. The @a cookie is optional. If non-NULL, you can - * supply a NULL @a recipient, and the recipient previously - * added with that cookie will be unlinked. - */ - virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient, - void* cookie = NULL, - uint32_t flags = 0, - wp<DeathRecipient>* outRecipient = NULL) = 0; - - virtual bool checkSubclass(const void* subclassID) const; - - typedef void (*object_cleanup_func)(const void* id, void* obj, void* cleanupCookie); - - virtual void attachObject( const void* objectID, - void* object, - void* cleanupCookie, - object_cleanup_func func) = 0; - virtual void* findObject(const void* objectID) const = 0; - virtual void detachObject(const void* objectID) = 0; - - virtual BBinder* localBinder(); - virtual BpBinder* remoteBinder(); - -protected: - inline virtual ~IBinder() { } - -private: -}; - -}; // namespace android - -// --------------------------------------------------------------------------- - -#endif // ANDROID_IBINDER_H diff --git a/include/utils/IInterface.h b/include/utils/IInterface.h deleted file mode 100644 index 959722a..0000000 --- a/include/utils/IInterface.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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_IINTERFACE_H -#define ANDROID_IINTERFACE_H - -#include <utils/Binder.h> - -namespace android { - -// ---------------------------------------------------------------------- - -class IInterface : public virtual RefBase -{ -public: - sp<IBinder> asBinder(); - sp<const IBinder> asBinder() const; - -protected: - virtual IBinder* onAsBinder() = 0; -}; - -// ---------------------------------------------------------------------- - -template<typename INTERFACE> -inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj) -{ - return INTERFACE::asInterface(obj); -} - -// ---------------------------------------------------------------------- - -template<typename INTERFACE> -class BnInterface : public INTERFACE, public BBinder -{ -public: - virtual sp<IInterface> queryLocalInterface(const String16& _descriptor); - virtual String16 getInterfaceDescriptor() const; - -protected: - virtual IBinder* onAsBinder(); -}; - -// ---------------------------------------------------------------------- - -template<typename INTERFACE> -class BpInterface : public INTERFACE, public BpRefBase -{ -public: - BpInterface(const sp<IBinder>& remote); - -protected: - virtual IBinder* onAsBinder(); -}; - -// ---------------------------------------------------------------------- - -#define DECLARE_META_INTERFACE(INTERFACE) \ - static const String16 descriptor; \ - static sp<I##INTERFACE> asInterface(const sp<IBinder>& obj); \ - virtual String16 getInterfaceDescriptor() const; \ - -#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \ - const String16 I##INTERFACE::descriptor(NAME); \ - String16 I##INTERFACE::getInterfaceDescriptor() const { \ - return I##INTERFACE::descriptor; \ - } \ - sp<I##INTERFACE> I##INTERFACE::asInterface(const sp<IBinder>& obj) \ - { \ - sp<I##INTERFACE> intr; \ - if (obj != NULL) { \ - intr = static_cast<I##INTERFACE*>( \ - obj->queryLocalInterface( \ - I##INTERFACE::descriptor).get()); \ - if (intr == NULL) { \ - intr = new Bp##INTERFACE(obj); \ - } \ - } \ - return intr; \ - } \ - -// ---------------------------------------------------------------------- -// No user-servicable parts after this... - -template<typename INTERFACE> -inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface( - const String16& _descriptor) -{ - if (_descriptor == INTERFACE::descriptor) return this; - return NULL; -} - -template<typename INTERFACE> -inline String16 BnInterface<INTERFACE>::getInterfaceDescriptor() const -{ - return INTERFACE::getInterfaceDescriptor(); -} - -template<typename INTERFACE> -IBinder* BnInterface<INTERFACE>::onAsBinder() -{ - return this; -} - -template<typename INTERFACE> -inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote) - : BpRefBase(remote) -{ -} - -template<typename INTERFACE> -inline IBinder* BpInterface<INTERFACE>::onAsBinder() -{ - return remote(); -} - -// ---------------------------------------------------------------------- - -}; // namespace android - -#endif // ANDROID_IINTERFACE_H diff --git a/include/utils/IMemory.h b/include/utils/IMemory.h deleted file mode 100644 index 35a3fd7..0000000 --- a/include/utils/IMemory.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2007 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_IMEMORY_H -#define ANDROID_IMEMORY_H - -#include <stdint.h> -#include <sys/types.h> -#include <sys/mman.h> - -#include <utils/RefBase.h> -#include <utils/Errors.h> -#include <utils/IInterface.h> - -namespace android { - -// ---------------------------------------------------------------------------- - -class IMemoryHeap : public IInterface -{ -public: - DECLARE_META_INTERFACE(MemoryHeap); - - // flags returned by getFlags() - enum { - READ_ONLY = 0x00000001, - MAP_ONCE = 0x00000002 - }; - - virtual int getHeapID() const = 0; - virtual void* getBase() const = 0; - virtual size_t getSize() const = 0; - virtual uint32_t getFlags() const = 0; - - // these are there just for backward source compatibility - int32_t heapID() const { return getHeapID(); } - void* base() const { return getBase(); } - size_t virtualSize() const { return getSize(); } -}; - -class BnMemoryHeap : public BnInterface<IMemoryHeap> -{ -public: - virtual status_t onTransact( - uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); -}; - -// ---------------------------------------------------------------------------- - -class IMemory : public IInterface -{ -public: - DECLARE_META_INTERFACE(Memory); - - virtual sp<IMemoryHeap> getMemory(ssize_t* offset=0, size_t* size=0) const = 0; - - // helpers - void* fastPointer(const sp<IBinder>& heap, ssize_t offset) const; - void* pointer() const; - size_t size() const; - ssize_t offset() const; -}; - -class BnMemory : public BnInterface<IMemory> -{ -public: - virtual status_t onTransact( - uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); -}; - -// ---------------------------------------------------------------------------- - -}; // namespace android - -#endif // ANDROID_IMEMORY_H diff --git a/include/utils/IPCThreadState.h b/include/utils/IPCThreadState.h deleted file mode 100644 index 0490fd3..0000000 --- a/include/utils/IPCThreadState.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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_IPC_THREAD_STATE_H -#define ANDROID_IPC_THREAD_STATE_H - -#include <utils/Errors.h> -#include <utils/Parcel.h> -#include <utils/ProcessState.h> -#include <utils/Vector.h> - -#ifdef HAVE_WIN32_PROC -typedef int uid_t; -#endif - -// --------------------------------------------------------------------------- -namespace android { - -class IPCThreadState -{ -public: - static IPCThreadState* self(); - - sp<ProcessState> process(); - - status_t clearLastError(); - - int getCallingPid(); - int getCallingUid(); - - int64_t clearCallingIdentity(); - void restoreCallingIdentity(int64_t token); - - void flushCommands(); - - void joinThreadPool(bool isMain = true); - - // Stop the local process. - void stopProcess(bool immediate = true); - - status_t transact(int32_t handle, - uint32_t code, const Parcel& data, - Parcel* reply, uint32_t flags); - - void incStrongHandle(int32_t handle); - void decStrongHandle(int32_t handle); - void incWeakHandle(int32_t handle); - void decWeakHandle(int32_t handle); - status_t attemptIncStrongHandle(int32_t handle); - static void expungeHandle(int32_t handle, IBinder* binder); - status_t requestDeathNotification( int32_t handle, - BpBinder* proxy); - status_t clearDeathNotification( int32_t handle, - BpBinder* proxy); - - static void shutdown(); - -private: - IPCThreadState(); - ~IPCThreadState(); - - status_t sendReply(const Parcel& reply, uint32_t flags); - status_t waitForResponse(Parcel *reply, - status_t *acquireResult=NULL); - status_t talkWithDriver(bool doReceive=true); - status_t writeTransactionData(int32_t cmd, - uint32_t binderFlags, - int32_t handle, - uint32_t code, - const Parcel& data, - status_t* statusBuffer); - status_t executeCommand(int32_t command); - - void clearCaller(); - - static void threadDestructor(void *st); - static void freeBuffer(Parcel* parcel, - const uint8_t* data, size_t dataSize, - const size_t* objects, size_t objectsSize, - void* cookie); - - const sp<ProcessState> mProcess; - Vector<BBinder*> mPendingStrongDerefs; - Vector<RefBase::weakref_type*> mPendingWeakDerefs; - - Parcel mIn; - Parcel mOut; - status_t mLastError; - pid_t mCallingPid; - uid_t mCallingUid; -}; - -}; // namespace android - -// --------------------------------------------------------------------------- - -#endif // ANDROID_IPC_THREAD_STATE_H diff --git a/include/utils/IPermissionController.h b/include/utils/IPermissionController.h deleted file mode 100644 index cb1dd34..0000000 --- a/include/utils/IPermissionController.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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_IPERMISSION_CONTROLLER_H -#define ANDROID_IPERMISSION_CONTROLLER_H - -#include <utils/IInterface.h> - -namespace android { - -// ---------------------------------------------------------------------- - -class IPermissionController : public IInterface -{ -public: - DECLARE_META_INTERFACE(PermissionController); - - virtual bool checkPermission(const String16& permission, - int32_t pid, int32_t uid) = 0; - - enum { - CHECK_PERMISSION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION - }; -}; - -// ---------------------------------------------------------------------- - -class BnPermissionController : public BnInterface<IPermissionController> -{ -public: - virtual status_t onTransact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); -}; - -// ---------------------------------------------------------------------- - -}; // namespace android - -#endif // ANDROID_IPERMISSION_CONTROLLER_H - diff --git a/include/utils/IServiceManager.h b/include/utils/IServiceManager.h deleted file mode 100644 index e3d99fe..0000000 --- a/include/utils/IServiceManager.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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_ISERVICE_MANAGER_H -#define ANDROID_ISERVICE_MANAGER_H - -#include <utils/IInterface.h> -#include <utils/IPermissionController.h> -#include <utils/Vector.h> -#include <utils/String16.h> - -namespace android { - -// ---------------------------------------------------------------------- - -class IServiceManager : public IInterface -{ -public: - DECLARE_META_INTERFACE(ServiceManager); - - /** - * Retrieve an existing service, blocking for a few seconds - * if it doesn't yet exist. - */ - virtual sp<IBinder> getService( const String16& name) const = 0; - - /** - * Retrieve an existing service, non-blocking. - */ - virtual sp<IBinder> checkService( const String16& name) const = 0; - - /** - * Register a service. - */ - virtual status_t addService( const String16& name, - const sp<IBinder>& service) = 0; - - /** - * Return list of all existing services. - */ - virtual Vector<String16> listServices() = 0; - - enum { - GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION, - CHECK_SERVICE_TRANSACTION, - ADD_SERVICE_TRANSACTION, - LIST_SERVICES_TRANSACTION, - }; -}; - -sp<IServiceManager> defaultServiceManager(); - -template<typename INTERFACE> -status_t getService(const String16& name, sp<INTERFACE>* outService) -{ - const sp<IServiceManager> sm = defaultServiceManager(); - if (sm != NULL) { - *outService = interface_cast<INTERFACE>(sm->getService(name)); - if ((*outService) != NULL) return NO_ERROR; - } - return NAME_NOT_FOUND; -} - -bool checkCallingPermission(const String16& permission); -bool checkCallingPermission(const String16& permission, - int32_t* outPid, int32_t* outUid); - -// ---------------------------------------------------------------------- - -class BnServiceManager : public BnInterface<IServiceManager> -{ -public: - virtual status_t onTransact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); -}; - -// ---------------------------------------------------------------------- - -}; // namespace android - -#endif // ANDROID_ISERVICE_MANAGER_H - diff --git a/include/utils/KeyedVector.h b/include/utils/KeyedVector.h index f4513ee..6bcdea4 100644 --- a/include/utils/KeyedVector.h +++ b/include/utils/KeyedVector.h @@ -164,7 +164,7 @@ ssize_t KeyedVector<KEY,VALUE>::replaceValueFor(const KEY& key, const VALUE& val template<typename KEY, typename VALUE> inline ssize_t KeyedVector<KEY,VALUE>::replaceValueAt(size_t index, const VALUE& item) { if (index<size()) { - mVector.editValueAt(index).value = item; + mVector.editItemAt(index).value = item; return index; } return BAD_INDEX; diff --git a/include/utils/List.h b/include/utils/List.h index 1a6be9a..403cd7f 100644 --- a/include/utils/List.h +++ b/include/utils/List.h @@ -22,147 +22,200 @@ // construction, so if the compiler's auto-generated versions won't work for // you, define your own. // -// The only class you want to use from here is "List". Do not use classes -// starting with "_" directly. +// The only class you want to use from here is "List". // #ifndef _LIBS_UTILS_LIST_H #define _LIBS_UTILS_LIST_H -namespace android { - -/* - * One element in the list. - */ -template<class T> class _ListNode { -public: - typedef _ListNode<T> _Node; - - _ListNode(const T& val) : mVal(val) {} - ~_ListNode(void) {} - - T& getRef(void) { return mVal; } - void setVal(const T& val) { mVal = val; } +#include <stddef.h> +#include <stdint.h> - _Node* getPrev(void) const { return mpPrev; } - void setPrev(_Node* ptr) { mpPrev = ptr; } - _Node* getNext(void) const { return mpNext; } - void setNext(_Node* ptr) { mpNext = ptr; } - -private: - T mVal; - _Node* mpPrev; - _Node* mpNext; -}; +namespace android { /* - * Iterator for walking through the list. + * Doubly-linked list. Instantiate with "List<MyClass> myList". + * + * Objects added to the list are copied using the assignment operator, + * so this must be defined. */ -template<class T, class Tref> class _ListIterator { -public: - typedef _ListIterator<T,Tref> _Iter; - typedef _ListNode<T> _Node; - - _ListIterator(void) {} - _ListIterator(_Node* ptr) : mpNode(ptr) {} - ~_ListIterator(void) {} - - /* - * Dereference operator. Used to get at the juicy insides. - */ - Tref operator*() const { return mpNode->getRef(); } - +template<typename T> +class List +{ +protected: /* - * Iterator comparison. + * One element in the list. */ - bool operator==(const _Iter& right) const { return mpNode == right.mpNode; } - bool operator!=(const _Iter& right) const { return mpNode != right.mpNode; } + class _Node { + public: + explicit _Node(const T& val) : mVal(val) {} + ~_Node() {} + inline T& getRef() { return mVal; } + inline const T& getRef() const { return mVal; } + inline _Node* getPrev() const { return mpPrev; } + inline _Node* getNext() const { return mpNext; } + inline void setVal(const T& val) { mVal = val; } + inline void setPrev(_Node* ptr) { mpPrev = ptr; } + inline void setNext(_Node* ptr) { mpNext = ptr; } + private: + friend class List; + friend class _ListIterator; + T mVal; + _Node* mpPrev; + _Node* mpNext; + }; /* - * Incr/decr, used to move through the list. + * Iterator for walking through the list. */ - _Iter& operator++(void) { // pre-increment - mpNode = mpNode->getNext(); - return *this; - } - _Iter operator++(int) { // post-increment - _Iter tmp = *this; - ++*this; - return tmp; - } - _Iter& operator--(void) { // pre-increment - mpNode = mpNode->getPrev(); - return *this; - } - _Iter operator--(int) { // post-increment - _Iter tmp = *this; - --*this; - return tmp; - } + + template <typename TYPE> + struct CONST_ITERATOR { + typedef _Node const * NodePtr; + typedef const TYPE Type; + }; + + template <typename TYPE> + struct NON_CONST_ITERATOR { + typedef _Node* NodePtr; + typedef TYPE Type; + }; + + template< + typename U, + template <class> class Constness + > + class _ListIterator { + typedef _ListIterator<U, Constness> _Iter; + typedef typename Constness<U>::NodePtr _NodePtr; + typedef typename Constness<U>::Type _Type; + + explicit _ListIterator(_NodePtr ptr) : mpNode(ptr) {} + + public: + _ListIterator() {} + _ListIterator(const _Iter& rhs) : mpNode(rhs.mpNode) {} + ~_ListIterator() {} + + // this will handle conversions from iterator to const_iterator + // (and also all convertible iterators) + // Here, in this implementation, the iterators can be converted + // if the nodes can be converted + template<typename V> explicit + _ListIterator(const V& rhs) : mpNode(rhs.mpNode) {} + + + /* + * Dereference operator. Used to get at the juicy insides. + */ + _Type& operator*() const { return mpNode->getRef(); } + _Type* operator->() const { return &(mpNode->getRef()); } + + /* + * Iterator comparison. + */ + inline bool operator==(const _Iter& right) const { + return mpNode == right.mpNode; } + + inline bool operator!=(const _Iter& right) const { + return mpNode != right.mpNode; } + + /* + * handle comparisons between iterator and const_iterator + */ + template<typename OTHER> + inline bool operator==(const OTHER& right) const { + return mpNode == right.mpNode; } + + template<typename OTHER> + inline bool operator!=(const OTHER& right) const { + return mpNode != right.mpNode; } + + /* + * Incr/decr, used to move through the list. + */ + inline _Iter& operator++() { // pre-increment + mpNode = mpNode->getNext(); + return *this; + } + const _Iter operator++(int) { // post-increment + _Iter tmp(*this); + mpNode = mpNode->getNext(); + return tmp; + } + inline _Iter& operator--() { // pre-increment + mpNode = mpNode->getPrev(); + return *this; + } + const _Iter operator--(int) { // post-increment + _Iter tmp(*this); + mpNode = mpNode->getPrev(); + return tmp; + } - _Node* getNode(void) const { return mpNode; } + inline _NodePtr getNode() const { return mpNode; } -private: - _Node* mpNode; -}; + _NodePtr mpNode; /* should be private, but older gcc fails */ + private: + friend class List; + }; - -/* - * Doubly-linked list. Instantiate with "List<MyClass> myList". - * - * Objects added to the list are copied using the assignment operator, - * so this must be defined. - */ -template<class T> class List { public: - typedef _ListNode<T> _Node; - - List(void) { + List() { prep(); } List(const List<T>& src) { // copy-constructor prep(); insert(begin(), src.begin(), src.end()); } - virtual ~List(void) { + virtual ~List() { clear(); delete[] (unsigned char*) mpMiddle; } - typedef _ListIterator<T,T&> iterator; - typedef _ListIterator<T, const T&> const_iterator; + typedef _ListIterator<T, NON_CONST_ITERATOR> iterator; + typedef _ListIterator<T, CONST_ITERATOR> const_iterator; List<T>& operator=(const List<T>& right); /* returns true if the list is empty */ - bool empty(void) const { return mpMiddle->getNext() == mpMiddle; } + inline bool empty() const { return mpMiddle->getNext() == mpMiddle; } /* return #of elements in list */ - unsigned int size(void) const { - return distance(begin(), end()); + size_t size() const { + return size_t(distance(begin(), end())); } /* * Return the first element or one past the last element. The - * _ListNode* we're returning is converted to an "iterator" by a + * _Node* we're returning is converted to an "iterator" by a * constructor in _ListIterator. */ - iterator begin() { return mpMiddle->getNext(); } - const_iterator begin() const { return mpMiddle->getNext(); } - iterator end() { return mpMiddle; } - const_iterator end() const { return mpMiddle; } + inline iterator begin() { + return iterator(mpMiddle->getNext()); + } + inline const_iterator begin() const { + return const_iterator(const_cast<_Node const*>(mpMiddle->getNext())); + } + inline iterator end() { + return iterator(mpMiddle); + } + inline const_iterator end() const { + return const_iterator(const_cast<_Node const*>(mpMiddle)); + } /* add the object to the head or tail of the list */ void push_front(const T& val) { insert(begin(), val); } void push_back(const T& val) { insert(end(), val); } /* insert before the current node; returns iterator at new node */ - iterator insert(iterator posn, const T& val) { + iterator insert(iterator posn, const T& val) + { _Node* newNode = new _Node(val); // alloc & copy-construct newNode->setNext(posn.getNode()); newNode->setPrev(posn.getNode()->getPrev()); posn.getNode()->getPrev()->setNext(newNode); posn.getNode()->setPrev(newNode); - return newNode; + return iterator(newNode); } /* insert a range of elements before the current node */ @@ -178,18 +231,18 @@ public: pPrev->setNext(pNext); pNext->setPrev(pPrev); delete posn.getNode(); - return pNext; + return iterator(pNext); } /* remove a range of elements */ iterator erase(iterator first, iterator last) { while (first != last) erase(first++); // don't erase than incr later! - return last; + return iterator(last); } /* remove all contents of the list */ - void clear(void) { + void clear() { _Node* pCurrent = mpMiddle->getNext(); _Node* pNext; @@ -207,21 +260,20 @@ public: * will be equal to "last". The iterators must refer to the same * list. * - * (This is actually a generic iterator function. It should be part - * of some other class, possibly an iterator base class. It needs to - * know the difference between a list, which has to march through, - * and a vector, which can just do pointer math.) + * FIXME: This is actually a generic iterator function. It should be a + * template function at the top-level with specializations for things like + * vector<>, which can just do pointer math). Here we limit it to + * _ListIterator of the same type but different constness. */ - unsigned int distance(iterator first, iterator last) { - unsigned int count = 0; - while (first != last) { - ++first; - ++count; - } - return count; - } - unsigned int distance(const_iterator first, const_iterator last) const { - unsigned int count = 0; + template< + typename U, + template <class> class CL, + template <class> class CR + > + ptrdiff_t distance( + _ListIterator<U, CL> first, _ListIterator<U, CR> last) const + { + ptrdiff_t count = 0; while (first != last) { ++first; ++count; @@ -231,12 +283,12 @@ public: private: /* - * I want a _ListNode but don't need it to hold valid data. More + * I want a _Node but don't need it to hold valid data. More * to the point, I don't want T's constructor to fire, since it * might have side-effects or require arguments. So, we do this * slightly uncouth storage alloc. */ - void prep(void) { + void prep() { mpMiddle = (_Node*) new unsigned char[sizeof(_Node)]; mpMiddle->setPrev(mpMiddle); mpMiddle->setNext(mpMiddle); diff --git a/include/utils/LogSocket.h b/include/utils/LogSocket.h deleted file mode 100644 index 01fbfb5..0000000 --- a/include/utils/LogSocket.h +++ /dev/null @@ -1,20 +0,0 @@ -/* utils/LogSocket.h -** -** Copyright 2008, The Android Open Source Project -** -** This file is dual licensed. It may be redistributed and/or modified -** under the terms of the Apache 2.0 License OR version 2 of the GNU -** General Public License. -*/ - -#ifndef _UTILS_LOGSOCKET_H -#define _UTILS_LOGSOCKET_H - -#define SOCKET_CLOSE_LOCAL 0 - -void add_send_stats(int fd, int send); -void add_recv_stats(int fd, int recv); -void log_socket_close(int fd, short reason); -void log_socket_connect(int fd, unsigned int ip, unsigned short port); - -#endif /* _UTILS_LOGSOCKET_H */ diff --git a/include/utils/MemoryBase.h b/include/utils/MemoryBase.h deleted file mode 100644 index eb5a9d2..0000000 --- a/include/utils/MemoryBase.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2008 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_MEMORY_BASE_H -#define ANDROID_MEMORY_BASE_H - -#include <stdlib.h> -#include <stdint.h> - -#include <utils/IMemory.h> - - -namespace android { - -// --------------------------------------------------------------------------- - -class MemoryBase : public BnMemory -{ -public: - MemoryBase(const sp<IMemoryHeap>& heap, ssize_t offset, size_t size); - virtual ~MemoryBase(); - virtual sp<IMemoryHeap> getMemory(ssize_t* offset, size_t* size) const; - -protected: - size_t getSize() const { return mSize; } - ssize_t getOffset() const { return mOffset; } - const sp<IMemoryHeap>& getHeap() const { return mHeap; } - -private: - size_t mSize; - ssize_t mOffset; - sp<IMemoryHeap> mHeap; -}; - -// --------------------------------------------------------------------------- -}; // namespace android - -#endif // ANDROID_MEMORY_BASE_H diff --git a/include/utils/MemoryDealer.h b/include/utils/MemoryDealer.h deleted file mode 100644 index 454b627..0000000 --- a/include/utils/MemoryDealer.h +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (C) 2007 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_MEMORY_DEALER_H -#define ANDROID_MEMORY_DEALER_H - - -#include <stdint.h> -#include <sys/types.h> - -#include <utils/IMemory.h> -#include <utils/threads.h> -#include <utils/MemoryHeapBase.h> - -namespace android { -// ---------------------------------------------------------------------------- -class String8; - -/* - * interface for implementing a "heap". A heap basically provides - * the IMemoryHeap interface for cross-process sharing and the - * ability to map/unmap pages within the heap. - */ -class HeapInterface : public virtual BnMemoryHeap -{ -public: - // all values must be page-aligned - virtual sp<IMemory> mapMemory(size_t offset, size_t size) = 0; -}; - -// ---------------------------------------------------------------------------- - -/* - * interface for implementing an allocator. An allocator provides - * methods for allocating and freeing memory blocks and dumping - * its state. - */ -class AllocatorInterface : public RefBase -{ -public: - enum { - PAGE_ALIGNED = 0x00000001 - }; - - virtual size_t allocate(size_t size, uint32_t flags = 0) = 0; - virtual status_t deallocate(size_t offset) = 0; - virtual size_t size() const = 0; - virtual void dump(const char* what, uint32_t flags = 0) const = 0; - virtual void dump(String8& res, - const char* what, uint32_t flags = 0) const = 0; -}; - -// ---------------------------------------------------------------------------- - -/* - * concrete implementation of HeapInterface on top of mmap() - */ -class SharedHeap : public HeapInterface, public MemoryHeapBase -{ -public: - SharedHeap(size_t size, uint32_t flags = 0, char const * name = NULL); - virtual ~SharedHeap(); - virtual sp<IMemory> mapMemory(size_t offset, size_t size); -}; - -// ---------------------------------------------------------------------------- - -/* - * A simple templatized doubly linked-list implementation - */ - -template <typename NODE> -class LinkedList -{ - NODE* mFirst; - NODE* mLast; - -public: - LinkedList() : mFirst(0), mLast(0) { } - bool isEmpty() const { return mFirst == 0; } - NODE const* head() const { return mFirst; } - NODE* head() { return mFirst; } - NODE const* tail() const { return mLast; } - NODE* tail() { return mLast; } - - void insertAfter(NODE* node, NODE* newNode) { - newNode->prev = node; - newNode->next = node->next; - if (node->next == 0) mLast = newNode; - else node->next->prev = newNode; - node->next = newNode; - } - - void insertBefore(NODE* node, NODE* newNode) { - newNode->prev = node->prev; - newNode->next = node; - if (node->prev == 0) mFirst = newNode; - else node->prev->next = newNode; - node->prev = newNode; - } - - void insertHead(NODE* newNode) { - if (mFirst == 0) { - mFirst = mLast = newNode; - newNode->prev = newNode->next = 0; - } else { - insertBefore(mFirst, newNode); - } - } - - void insertTail(NODE* newNode) { - if (mLast == 0) insertBeginning(newNode); - else insertAfter(mLast, newNode); - } - - NODE* remove(NODE* node) { - if (node->prev == 0) mFirst = node->next; - else node->prev->next = node->next; - if (node->next == 0) mLast = node->prev; - else node->next->prev = node->prev; - return node; - } -}; - - -/* - * concrete implementation of AllocatorInterface using a simple - * best-fit allocation scheme - */ -class SimpleBestFitAllocator : public AllocatorInterface -{ -public: - - SimpleBestFitAllocator(size_t size); - virtual ~SimpleBestFitAllocator(); - - virtual size_t allocate(size_t size, uint32_t flags = 0); - virtual status_t deallocate(size_t offset); - virtual size_t size() const; - virtual void dump(const char* what, uint32_t flags = 0) const; - virtual void dump(String8& res, - const char* what, uint32_t flags = 0) const; - -private: - - struct chunk_t { - chunk_t(size_t start, size_t size) - : start(start), size(size), free(1), prev(0), next(0) { - } - size_t start; - size_t size : 28; - int free : 4; - mutable chunk_t* prev; - mutable chunk_t* next; - }; - - ssize_t alloc(size_t size, uint32_t flags); - chunk_t* dealloc(size_t start); - void dump_l(const char* what, uint32_t flags = 0) const; - void dump_l(String8& res, const char* what, uint32_t flags = 0) const; - - static const int kMemoryAlign; - mutable Mutex mLock; - LinkedList<chunk_t> mList; - size_t mHeapSize; -}; - -// ---------------------------------------------------------------------------- - -class MemoryDealer : public RefBase -{ -public: - - enum { - READ_ONLY = MemoryHeapBase::READ_ONLY, - PAGE_ALIGNED = AllocatorInterface::PAGE_ALIGNED - }; - - // creates a memory dealer with the SharedHeap and SimpleBestFitAllocator - MemoryDealer(size_t size, uint32_t flags = 0, const char* name = 0); - - // provide a custom heap but use the SimpleBestFitAllocator - MemoryDealer(const sp<HeapInterface>& heap); - - // provide both custom heap and allocotar - MemoryDealer( - const sp<HeapInterface>& heap, - const sp<AllocatorInterface>& allocator); - - virtual ~MemoryDealer(); - - virtual sp<IMemory> allocate(size_t size, uint32_t flags = 0); - virtual void deallocate(size_t offset); - virtual void dump(const char* what, uint32_t flags = 0) const; - - - sp<IMemoryHeap> getMemoryHeap() const { return heap(); } - sp<AllocatorInterface> getAllocator() const { return allocator(); } - -private: - const sp<HeapInterface>& heap() const; - const sp<AllocatorInterface>& allocator() const; - - class Allocation : public BnMemory { - public: - Allocation(const sp<MemoryDealer>& dealer, - ssize_t offset, size_t size, const sp<IMemory>& memory); - virtual ~Allocation(); - virtual sp<IMemoryHeap> getMemory(ssize_t* offset, size_t* size) const; - private: - sp<MemoryDealer> mDealer; - ssize_t mOffset; - size_t mSize; - sp<IMemory> mMemory; - }; - - sp<HeapInterface> mHeap; - sp<AllocatorInterface> mAllocator; -}; - - -// ---------------------------------------------------------------------------- -}; // namespace android - -#endif // ANDROID_MEMORY_DEALER_H diff --git a/include/utils/MemoryHeapBase.h b/include/utils/MemoryHeapBase.h deleted file mode 100644 index 574acf4..0000000 --- a/include/utils/MemoryHeapBase.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2008 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_MEMORY_HEAP_BASE_H -#define ANDROID_MEMORY_HEAP_BASE_H - -#include <stdlib.h> -#include <stdint.h> - -#include <utils/IMemory.h> - - -namespace android { - -// --------------------------------------------------------------------------- - -class MemoryHeapBase : public virtual BnMemoryHeap -{ -public: - enum { - READ_ONLY = IMemoryHeap::READ_ONLY, - MAP_ONCE = IMemoryHeap::MAP_ONCE, - // memory won't be mapped locally, but will be mapped in the remote - // process. - DONT_MAP_LOCALLY = 0x00000100 - }; - - /* - * maps the memory referenced by fd. but DOESN'T take ownership - * of the filedescriptor (it makes a copy with dup() - */ - MemoryHeapBase(int fd, size_t size, uint32_t flags = 0); - - /* - * maps memory from the given device - */ - MemoryHeapBase(const char* device, size_t size = 0, uint32_t flags = 0); - - /* - * maps memory from ashmem, with the given name for debugging - */ - MemoryHeapBase(size_t size, uint32_t flags = 0, char const* name = NULL); - - virtual ~MemoryHeapBase(); - - /* implement IMemoryHeap interface */ - virtual int getHeapID() const; - virtual void* getBase() const; - virtual size_t getSize() const; - virtual uint32_t getFlags() const; - - const char* getDevice() const; - - /* this closes this heap -- use carefully */ - void dispose(); - - /* this is only needed as a workaround, use only if you know - * what you are doing */ - status_t setDevice(const char* device) { - if (mDevice == 0) - mDevice = device; - return mDevice ? NO_ERROR : ALREADY_EXISTS; - } - -protected: - MemoryHeapBase(); - // init() takes ownership of fd - status_t init(int fd, void *base, int size, - int flags = 0, const char* device = NULL); - -private: - status_t mapfd(int fd, size_t size); - - int mFD; - size_t mSize; - void* mBase; - uint32_t mFlags; - const char* mDevice; - bool mNeedUnmap; -}; - -// --------------------------------------------------------------------------- -}; // namespace android - -#endif // ANDROID_MEMORY_HEAP_BASE_H diff --git a/include/utils/MemoryHeapPmem.h b/include/utils/MemoryHeapPmem.h deleted file mode 100644 index 60335ad..0000000 --- a/include/utils/MemoryHeapPmem.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2008 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_MEMORY_HEAP_PMEM_H -#define ANDROID_MEMORY_HEAP_PMEM_H - -#include <stdlib.h> -#include <stdint.h> - -#include <utils/MemoryDealer.h> -#include <utils/MemoryHeapBase.h> -#include <utils/IMemory.h> -#include <utils/SortedVector.h> - -namespace android { - -class MemoryHeapBase; - -// --------------------------------------------------------------------------- - -class MemoryHeapPmem : public HeapInterface, public MemoryHeapBase -{ -public: - class MemoryPmem : public BnMemory { - public: - MemoryPmem(const sp<MemoryHeapPmem>& heap); - ~MemoryPmem(); - protected: - const sp<MemoryHeapPmem>& getHeap() const { return mClientHeap; } - private: - friend class MemoryHeapPmem; - virtual void revoke() = 0; - sp<MemoryHeapPmem> mClientHeap; - }; - - MemoryHeapPmem(const sp<MemoryHeapBase>& pmemHeap, - uint32_t flags = IMemoryHeap::MAP_ONCE); - ~MemoryHeapPmem(); - - /* HeapInterface additions */ - virtual sp<IMemory> mapMemory(size_t offset, size_t size); - - /* make the whole heap visible (you know who you are) */ - virtual status_t slap(); - - /* hide (revoke) the whole heap (the client will see the garbage page) */ - virtual status_t unslap(); - - /* revoke all allocations made by this heap */ - virtual void revoke(); - -private: - /* use this to create your own IMemory for mapMemory */ - virtual sp<MemoryPmem> createMemory(size_t offset, size_t size); - void remove(const wp<MemoryPmem>& memory); - -private: - sp<MemoryHeapBase> mParentHeap; - mutable Mutex mLock; - SortedVector< wp<MemoryPmem> > mAllocations; -}; - - -// --------------------------------------------------------------------------- -}; // namespace android - -#endif // ANDROID_MEMORY_HEAP_PMEM_H diff --git a/include/utils/Parcel.h b/include/utils/Parcel.h deleted file mode 100644 index af1490a..0000000 --- a/include/utils/Parcel.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * 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; - -struct flat_binder_object; // defined in support_p/binder_module.h - -class 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; - - 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 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); - - // 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; - - 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; - - - // 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; - - 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 diff --git a/include/utils/Pipe.h b/include/utils/Pipe.h deleted file mode 100644 index 6404168..0000000 --- a/include/utils/Pipe.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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. - */ - -// -// FIFO I/O. -// -#ifndef _LIBS_UTILS_PIPE_H -#define _LIBS_UTILS_PIPE_H - -#ifdef HAVE_ANDROID_OS -#error DO NOT USE THIS FILE IN THE DEVICE BUILD -#endif - -namespace android { - -/* - * Simple anonymous unidirectional pipe. - * - * The primary goal is to create an implementation with minimal overhead - * under Linux. Making Windows, Mac OS X, and Linux all work the same way - * is a secondary goal. Part of this goal is to have something that can - * be fed to a select() call, so that the application can sleep in the - * kernel until something interesting happens. - */ -class Pipe { -public: - Pipe(void); - virtual ~Pipe(void); - - /* Create the pipe */ - bool create(void); - - /* Create a read-only pipe, using the supplied handle as read handle */ - bool createReader(unsigned long handle); - /* Create a write-only pipe, using the supplied handle as write handle */ - bool createWriter(unsigned long handle); - - /* Is this object ready to go? */ - bool isCreated(void); - - /* - * Read "count" bytes from the pipe. Returns the amount of data read, - * or 0 if no data available and we're non-blocking. - * Returns -1 on error. - */ - int read(void* buf, int count); - - /* - * Write "count" bytes into the pipe. Returns number of bytes written, - * or 0 if there's no room for more data and we're non-blocking. - * Returns -1 on error. - */ - int write(const void* buf, int count); - - /* Returns "true" if data is available to read */ - bool readReady(void); - - /* Enable or disable non-blocking I/O for reads */ - bool setReadNonBlocking(bool val); - /* Enable or disable non-blocking I/O for writes. Only works on Linux. */ - bool setWriteNonBlocking(bool val); - - /* - * Get the handle. Only useful in some platform-specific situations. - */ - unsigned long getReadHandle(void); - unsigned long getWriteHandle(void); - - /* - * Modify inheritance, i.e. whether or not a child process will get - * copies of the descriptors. Systems with fork+exec allow us to close - * the descriptors before launching the child process, but Win32 - * doesn't allow it. - */ - bool disallowReadInherit(void); - bool disallowWriteInherit(void); - - /* - * Close one side or the other. Useful in the parent after launching - * a child process. - */ - bool closeRead(void); - bool closeWrite(void); - -private: - bool mReadNonBlocking; - bool mWriteNonBlocking; - - unsigned long mReadHandle; - unsigned long mWriteHandle; -}; - -}; // android - -#endif // _LIBS_UTILS_PIPE_H diff --git a/include/utils/ProcessState.h b/include/utils/ProcessState.h deleted file mode 100644 index 39584f4..0000000 --- a/include/utils/ProcessState.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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_PROCESS_STATE_H -#define ANDROID_PROCESS_STATE_H - -#include <utils/IBinder.h> -#include <utils/KeyedVector.h> -#include <utils/String8.h> -#include <utils/String16.h> - -#include <utils/threads.h> - -// --------------------------------------------------------------------------- -namespace android { - -// Global variables -extern int mArgC; -extern const char* const* mArgV; -extern int mArgLen; - -class IPCThreadState; - -class ProcessState : public virtual RefBase -{ -public: - static sp<ProcessState> self(); - - static void setSingleProcess(bool singleProcess); - - void setContextObject(const sp<IBinder>& object); - sp<IBinder> getContextObject(const sp<IBinder>& caller); - - void setContextObject(const sp<IBinder>& object, - const String16& name); - sp<IBinder> getContextObject(const String16& name, - const sp<IBinder>& caller); - - bool supportsProcesses() const; - - void startThreadPool(); - - typedef bool (*context_check_func)(const String16& name, - const sp<IBinder>& caller, - void* userData); - - bool isContextManager(void) const; - bool becomeContextManager( - context_check_func checkFunc, - void* userData); - - sp<IBinder> getStrongProxyForHandle(int32_t handle); - wp<IBinder> getWeakProxyForHandle(int32_t handle); - void expungeHandle(int32_t handle, IBinder* binder); - - void setArgs(int argc, const char* const argv[]); - int getArgC() const; - const char* const* getArgV() const; - - void setArgV0(const char* txt); - - void spawnPooledThread(bool isMain); - -private: - friend class IPCThreadState; - - ProcessState(); - ~ProcessState(); - - ProcessState(const ProcessState& o); - ProcessState& operator=(const ProcessState& o); - - struct handle_entry { - IBinder* binder; - RefBase::weakref_type* refs; - }; - - handle_entry* lookupHandleLocked(int32_t handle); - - int mDriverFD; - void* mVMStart; - - mutable Mutex mLock; // protects everything below. - - Vector<handle_entry>mHandleToObject; - - bool mManagesContexts; - context_check_func mBinderContextCheckFunc; - void* mBinderContextUserData; - - KeyedVector<String16, sp<IBinder> > - mContexts; - - - String8 mRootDir; - bool mThreadPoolStarted; - volatile int32_t mThreadPoolSeq; -}; - -}; // namespace android - -// --------------------------------------------------------------------------- - -#endif // ANDROID_PROCESS_STATE_H diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h index cbda0fd..bd7f28c 100644 --- a/include/utils/RefBase.h +++ b/include/utils/RefBase.h @@ -156,6 +156,10 @@ public: delete static_cast<const T*>(this); } } + //! DEBUGGING ONLY: Get current strong ref count. + inline int32_t getStrongCount() const { + return mCount; + } protected: inline ~LightRefBase() { } diff --git a/include/utils/Singleton.h b/include/utils/Singleton.h new file mode 100644 index 0000000..bc7626a8 --- /dev/null +++ b/include/utils/Singleton.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2007 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_UTILS_SINGLETON_H +#define ANDROID_UTILS_SINGLETON_H + +#include <stdint.h> +#include <sys/types.h> +#include <utils/threads.h> + +namespace android { +// --------------------------------------------------------------------------- + +template <typename TYPE> +class Singleton +{ +public: + static TYPE& getInstance() { + Mutex::Autolock _l(sLock); + TYPE* instance = sInstance; + if (instance == 0) { + instance = new TYPE(); + sInstance = instance; + } + return *instance; + } + +protected: + ~Singleton() { }; + Singleton() { }; + +private: + Singleton(const Singleton&); + Singleton& operator = (const Singleton&); + static Mutex sLock; + static TYPE* sInstance; +}; + +/* + * use ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) in your implementation file + * (eg: <TYPE>.cpp) to create the static instance of Singleton<>'s attributes, + * and avoid to have a copy of them in each compilation units Singleton<TYPE> + * is used. + */ + +#define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) \ + template class Singleton< TYPE >; \ + template< class TYPE > Mutex Singleton< TYPE >::sLock; \ + template<> TYPE* Singleton< TYPE >::sInstance(0); + + +// --------------------------------------------------------------------------- +}; // namespace android + +#endif // ANDROID_UTILS_SINGLETON_H + diff --git a/include/utils/Socket.h b/include/utils/Socket.h deleted file mode 100644 index 8b7f406..0000000 --- a/include/utils/Socket.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - */ - -// -// Socket class. Modeled after Java classes. -// -#ifndef _RUNTIME_SOCKET_H -#define _RUNTIME_SOCKET_H - -#include <utils/inet_address.h> -#include <sys/types.h> - -namespace android { - -/* - * Basic socket class, needed to abstract away the differences between - * BSD sockets and WinSock. This establishes a streaming network - * connection (TCP/IP) to somebody. - */ -class Socket { -public: - Socket(void); - ~Socket(void); - - // Create a connection to somewhere. - // Return 0 on success. - int connect(const char* host, int port); - int connect(const InetAddress* addr, int port); - - - // Close the socket. Don't try to use this object again after - // calling this. Returns false on failure. - bool close(void); - - // If we created the socket without an address, we can use these - // to finish the connection. Returns 0 on success. - int bind(const SocketAddress& bindPoint); - int connect(const SocketAddress& endPoint); - - // Here we deviate from the traditional object-oriented fanciness - // and just provide read/write operators instead of getters for - // objects that abstract a stream. - // - // Standard read/write semantics. - int read(void* buf, ssize_t len) const; - int write(const void* buf, ssize_t len) const; - - // This must be called once, at program startup. - static bool bootInit(void); - static void finalShutdown(void); - -private: - // Internal function that establishes a connection. - int doConnect(const InetSocketAddress& addr); - - unsigned long mSock; // holds SOCKET or int - - static bool mBootInitialized; -}; - - -// debug -- unit tests -void TestSockets(void); - -}; // namespace android - -#endif // _RUNTIME_SOCKET_H diff --git a/include/utils/SortedVector.h b/include/utils/SortedVector.h index c8a6153..8beec57 100644 --- a/include/utils/SortedVector.h +++ b/include/utils/SortedVector.h @@ -141,8 +141,7 @@ SortedVector<TYPE>::SortedVector() : SortedVectorImpl(sizeof(TYPE), ((traits<TYPE>::has_trivial_ctor ? HAS_TRIVIAL_CTOR : 0) |(traits<TYPE>::has_trivial_dtor ? HAS_TRIVIAL_DTOR : 0) - |(traits<TYPE>::has_trivial_copy ? HAS_TRIVIAL_COPY : 0) - |(traits<TYPE>::has_trivial_assign ? HAS_TRIVIAL_ASSIGN : 0)) + |(traits<TYPE>::has_trivial_copy ? HAS_TRIVIAL_COPY : 0)) ) { } diff --git a/include/utils/StringArray.h b/include/utils/StringArray.h new file mode 100644 index 0000000..c244587 --- /dev/null +++ b/include/utils/StringArray.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2009 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. + */ + +// +// Sortable array of strings. STL-ish, but STL-free. +// +#ifndef _LIBS_UTILS_STRING_ARRAY_H +#define _LIBS_UTILS_STRING_ARRAY_H + +#include <stdlib.h> +#include <string.h> + +namespace android { + +// +// An expanding array of strings. Add, get, sort, delete. +// +class StringArray { +public: + StringArray(); + virtual ~StringArray(); + + // + // Add a string. A copy of the string is made. + // + bool push_back(const char* str); + + // + // Delete an entry. + // + void erase(int idx); + + // + // Sort the array. + // + void sort(int (*compare)(const void*, const void*)); + + // + // Pass this to the sort routine to do an ascending alphabetical sort. + // + static int cmpAscendingAlpha(const void* pstr1, const void* pstr2); + + // + // Get the #of items in the array. + // + inline int size(void) const { return mCurrent; } + + // + // Return entry N. + // [should use operator[] here] + // + const char* getEntry(int idx) const { + return (unsigned(idx) >= unsigned(mCurrent)) ? NULL : mArray[idx]; + } + + // + // Set entry N to specified string. + // [should use operator[] here] + // + void setEntry(int idx, const char* str); + +private: + int mMax; + int mCurrent; + char** mArray; +}; + +}; // namespace android + +#endif // _LIBS_UTILS_STRING_ARRAY_H diff --git a/include/utils/TextOutput.h b/include/utils/TextOutput.h index d8d86ba..de2fbbe 100644 --- a/include/utils/TextOutput.h +++ b/include/utils/TextOutput.h @@ -28,8 +28,8 @@ namespace android { class TextOutput { public: - TextOutput() { } - virtual ~TextOutput() { } + TextOutput(); + virtual ~TextOutput(); virtual status_t print(const char* txt, size_t len) = 0; virtual void moveIndent(int delta) = 0; diff --git a/include/utils/TimerProbe.h b/include/utils/TimerProbe.h deleted file mode 100644 index f2e32b2..0000000 --- a/include/utils/TimerProbe.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2007 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_TIMER_PROBE_H -#define ANDROID_TIMER_PROBE_H - -#if 0 && defined(HAVE_POSIX_CLOCKS) -#define ENABLE_TIMER_PROBE 1 -#else -#define ENABLE_TIMER_PROBE 0 -#endif - -#if ENABLE_TIMER_PROBE - -#include <time.h> -#include <sys/time.h> -#include <utils/Vector.h> - -#define TIMER_PROBE(tag) \ - static int _timer_slot_; \ - android::TimerProbe probe(tag, &_timer_slot_) -#define TIMER_PROBE_END() probe.end() -#else -#define TIMER_PROBE(tag) -#define TIMER_PROBE_END() -#endif - -#if ENABLE_TIMER_PROBE -namespace android { - -class TimerProbe { -public: - TimerProbe(const char tag[], int* slot); - void end(); - ~TimerProbe(); -private: - struct Bucket { - int mStart, mReal, mProcess, mThread, mCount; - const char* mTag; - int* mSlotPtr; - int mIndent; - }; - static Vector<Bucket> gBuckets; - static TimerProbe* gExecuteChain; - static int gIndent; - static timespec gRealBase; - TimerProbe* mNext; - static uint32_t ElapsedTime(const timespec& start, const timespec& end); - void print(const timespec& r, const timespec& p, const timespec& t) const; - timespec mRealStart, mPStart, mTStart; - const char* mTag; - int mIndent; - int mBucket; -}; - -}; // namespace android - -#endif -#endif diff --git a/include/utils/Timers.h b/include/utils/Timers.h index 9610399..9a9e07c 100644 --- a/include/utils/Timers.h +++ b/include/utils/Timers.h @@ -88,9 +88,6 @@ nsecs_t systemTime(int clock = SYSTEM_TIME_MONOTONIC); nsecs_t systemTime(int clock); #endif // def __cplusplus -// return the system-time according to the specified clock -int sleepForInterval(long interval, struct timeval* pNextTick); - #ifdef __cplusplus } // extern "C" #endif @@ -108,15 +105,15 @@ namespace android { */ class DurationTimer { public: - DurationTimer(void) {} - ~DurationTimer(void) {} + DurationTimer() {} + ~DurationTimer() {} // Start the timer. - void start(void); + void start(); // Stop the timer. - void stop(void); + void stop(); // Get the duration in microseconds. - long long durationUsecs(void) const; + long long durationUsecs() const; // Subtract two timevals. Returns the difference (ptv1-ptv2) in // microseconds. diff --git a/include/utils/TypeHelpers.h b/include/utils/TypeHelpers.h index c04c37f..2ff2749 100644 --- a/include/utils/TypeHelpers.h +++ b/include/utils/TypeHelpers.h @@ -29,35 +29,39 @@ namespace android { /* * Types traits */ - -template <typename T> struct trait_trivial_ctor { enum { value = false }; }; -template <typename T> struct trait_trivial_dtor { enum { value = false }; }; -template <typename T> struct trait_trivial_copy { enum { value = false }; }; -template <typename T> struct trait_trivial_assign{ enum { value = false }; }; - -template <typename T> struct trait_pointer { enum { value = false }; }; -template <typename T> struct trait_pointer<T*> { enum { value = true }; }; - -#define ANDROID_BASIC_TYPES_TRAITS( T ) \ - template<> struct trait_trivial_ctor< T > { enum { value = true }; }; \ - template<> struct trait_trivial_dtor< T > { enum { value = true }; }; \ - template<> struct trait_trivial_copy< T > { enum { value = true }; }; \ - template<> struct trait_trivial_assign< T >{ enum { value = true }; }; - -#define ANDROID_TYPE_TRAITS( T, ctor, dtor, copy, assign ) \ - template<> struct trait_trivial_ctor< T > { enum { value = ctor }; }; \ - template<> struct trait_trivial_dtor< T > { enum { value = dtor }; }; \ - template<> struct trait_trivial_copy< T > { enum { value = copy }; }; \ - template<> struct trait_trivial_assign< T >{ enum { value = assign }; }; + +template <typename T> struct trait_trivial_ctor { enum { value = false }; }; +template <typename T> struct trait_trivial_dtor { enum { value = false }; }; +template <typename T> struct trait_trivial_copy { enum { value = false }; }; +template <typename T> struct trait_trivial_move { enum { value = false }; }; +template <typename T> struct trait_pointer { enum { value = false }; }; +template <typename T> struct trait_pointer<T*> { enum { value = true }; }; + +// sp<> can be trivially moved +template <typename T> class sp; +template <typename T> struct trait_trivial_move< sp<T> >{ + enum { value = true }; +}; + +// wp<> can be trivially moved +template <typename T> class wp; +template <typename T> struct trait_trivial_move< wp<T> >{ + enum { value = true }; +}; template <typename TYPE> struct traits { enum { + // whether this type is a pointer is_pointer = trait_pointer<TYPE>::value, + // whether this type's constructor is a no-op has_trivial_ctor = is_pointer || trait_trivial_ctor<TYPE>::value, + // whether this type's destructor is a no-op has_trivial_dtor = is_pointer || trait_trivial_dtor<TYPE>::value, + // whether this type type can be copy-constructed with memcpy has_trivial_copy = is_pointer || trait_trivial_copy<TYPE>::value, - has_trivial_assign = is_pointer || trait_trivial_assign<TYPE>::value + // whether this type can be moved with memmove + has_trivial_move = is_pointer || trait_trivial_move<TYPE>::value }; }; @@ -65,37 +69,47 @@ template <typename T, typename U> struct aggregate_traits { enum { is_pointer = false, - has_trivial_ctor = traits<T>::has_trivial_ctor && traits<U>::has_trivial_ctor, - has_trivial_dtor = traits<T>::has_trivial_dtor && traits<U>::has_trivial_dtor, - has_trivial_copy = traits<T>::has_trivial_copy && traits<U>::has_trivial_copy, - has_trivial_assign = traits<T>::has_trivial_assign && traits<U>::has_trivial_assign + has_trivial_ctor = + traits<T>::has_trivial_ctor && traits<U>::has_trivial_ctor, + has_trivial_dtor = + traits<T>::has_trivial_dtor && traits<U>::has_trivial_dtor, + has_trivial_copy = + traits<T>::has_trivial_copy && traits<U>::has_trivial_copy, + has_trivial_move = + traits<T>::has_trivial_move && traits<U>::has_trivial_move }; }; +#define ANDROID_BASIC_TYPES_TRAITS( T ) \ + template<> struct trait_trivial_ctor< T > { enum { value = true }; }; \ + template<> struct trait_trivial_dtor< T > { enum { value = true }; }; \ + template<> struct trait_trivial_copy< T > { enum { value = true }; }; \ + template<> struct trait_trivial_move< T > { enum { value = true }; }; + // --------------------------------------------------------------------------- /* * basic types traits */ - -ANDROID_BASIC_TYPES_TRAITS( void ); -ANDROID_BASIC_TYPES_TRAITS( bool ); -ANDROID_BASIC_TYPES_TRAITS( char ); -ANDROID_BASIC_TYPES_TRAITS( unsigned char ); -ANDROID_BASIC_TYPES_TRAITS( short ); -ANDROID_BASIC_TYPES_TRAITS( unsigned short ); -ANDROID_BASIC_TYPES_TRAITS( int ); -ANDROID_BASIC_TYPES_TRAITS( unsigned int ); -ANDROID_BASIC_TYPES_TRAITS( long ); -ANDROID_BASIC_TYPES_TRAITS( unsigned long ); -ANDROID_BASIC_TYPES_TRAITS( long long ); -ANDROID_BASIC_TYPES_TRAITS( unsigned long long ); -ANDROID_BASIC_TYPES_TRAITS( float ); -ANDROID_BASIC_TYPES_TRAITS( double ); + +ANDROID_BASIC_TYPES_TRAITS( void ) +ANDROID_BASIC_TYPES_TRAITS( bool ) +ANDROID_BASIC_TYPES_TRAITS( char ) +ANDROID_BASIC_TYPES_TRAITS( unsigned char ) +ANDROID_BASIC_TYPES_TRAITS( short ) +ANDROID_BASIC_TYPES_TRAITS( unsigned short ) +ANDROID_BASIC_TYPES_TRAITS( int ) +ANDROID_BASIC_TYPES_TRAITS( unsigned int ) +ANDROID_BASIC_TYPES_TRAITS( long ) +ANDROID_BASIC_TYPES_TRAITS( unsigned long ) +ANDROID_BASIC_TYPES_TRAITS( long long ) +ANDROID_BASIC_TYPES_TRAITS( unsigned long long ) +ANDROID_BASIC_TYPES_TRAITS( float ) +ANDROID_BASIC_TYPES_TRAITS( double ) // --------------------------------------------------------------------------- - + /* * compare and order types */ @@ -111,9 +125,9 @@ int compare_type(const TYPE& lhs, const TYPE& rhs) { } /* - * create, destroy, copy and assign types... + * create, destroy, copy and move types... */ - + template<typename TYPE> inline void construct_type(TYPE* p, size_t n) { if (!traits<TYPE>::has_trivial_ctor) { @@ -146,17 +160,6 @@ void copy_type(TYPE* d, const TYPE* s, size_t n) { } template<typename TYPE> inline -void assign_type(TYPE* d, const TYPE* s, size_t n) { - if (!traits<TYPE>::has_trivial_assign) { - while (n--) { - *d++ = *s++; - } - } else { - memcpy(d,s,n*sizeof(TYPE)); - } -} - -template<typename TYPE> inline void splat_type(TYPE* where, const TYPE* what, size_t n) { if (!traits<TYPE>::has_trivial_copy) { while (n--) { @@ -164,15 +167,19 @@ void splat_type(TYPE* where, const TYPE* what, size_t n) { where++; } } else { - while (n--) { - *where++ = *what; + while (n--) { + *where++ = *what; } } } template<typename TYPE> inline void move_forward_type(TYPE* d, const TYPE* s, size_t n = 1) { - if (!traits<TYPE>::has_trivial_copy || !traits<TYPE>::has_trivial_dtor) { + if ((traits<TYPE>::has_trivial_dtor && traits<TYPE>::has_trivial_copy) + || traits<TYPE>::has_trivial_move) + { + memmove(d,s,n*sizeof(TYPE)); + } else { d += n; s += n; while (n--) { @@ -180,35 +187,37 @@ void move_forward_type(TYPE* d, const TYPE* s, size_t n = 1) { if (!traits<TYPE>::has_trivial_copy) { new(d) TYPE(*s); } else { - *d = *s; + *d = *s; } if (!traits<TYPE>::has_trivial_dtor) { s->~TYPE(); } } - } else { - memmove(d,s,n*sizeof(TYPE)); } } template<typename TYPE> inline void move_backward_type(TYPE* d, const TYPE* s, size_t n = 1) { - if (!traits<TYPE>::has_trivial_copy || !traits<TYPE>::has_trivial_dtor) { + if ((traits<TYPE>::has_trivial_dtor && traits<TYPE>::has_trivial_copy) + || traits<TYPE>::has_trivial_move) + { + memmove(d,s,n*sizeof(TYPE)); + } else { while (n--) { if (!traits<TYPE>::has_trivial_copy) { new(d) TYPE(*s); } else { - *d = *s; + *d = *s; } if (!traits<TYPE>::has_trivial_dtor) { s->~TYPE(); } d++, s++; } - } else { - memmove(d,s,n*sizeof(TYPE)); } } + + // --------------------------------------------------------------------------- /* @@ -242,8 +251,8 @@ struct trait_trivial_copy< key_value_pair_t<K, V> > { enum { value = aggregate_traits<K,V>::has_trivial_copy }; }; template<> template <typename K, typename V> -struct trait_trivial_assign< key_value_pair_t<K, V> > -{ enum { value = aggregate_traits<K,V>::has_trivial_assign};}; +struct trait_trivial_move< key_value_pair_t<K, V> > +{ enum { value = aggregate_traits<K,V>::has_trivial_move }; }; // --------------------------------------------------------------------------- diff --git a/include/utils/Vector.h b/include/utils/Vector.h index be365d8..ad59fd6 100644 --- a/include/utils/Vector.h +++ b/include/utils/Vector.h @@ -175,8 +175,7 @@ Vector<TYPE>::Vector() : VectorImpl(sizeof(TYPE), ((traits<TYPE>::has_trivial_ctor ? HAS_TRIVIAL_CTOR : 0) |(traits<TYPE>::has_trivial_dtor ? HAS_TRIVIAL_DTOR : 0) - |(traits<TYPE>::has_trivial_copy ? HAS_TRIVIAL_COPY : 0) - |(traits<TYPE>::has_trivial_assign ? HAS_TRIVIAL_ASSIGN : 0)) + |(traits<TYPE>::has_trivial_copy ? HAS_TRIVIAL_COPY : 0)) ) { } diff --git a/include/utils/VectorImpl.h b/include/utils/VectorImpl.h index 2525229..49b03f1 100644 --- a/include/utils/VectorImpl.h +++ b/include/utils/VectorImpl.h @@ -44,7 +44,6 @@ public: HAS_TRIVIAL_CTOR = 0x00000001, HAS_TRIVIAL_DTOR = 0x00000002, HAS_TRIVIAL_COPY = 0x00000004, - HAS_TRIVIAL_ASSIGN = 0x00000008 }; VectorImpl(size_t itemSize, uint32_t flags); diff --git a/include/utils/ZipEntry.h b/include/utils/ZipEntry.h deleted file mode 100644 index e4698df..0000000 --- a/include/utils/ZipEntry.h +++ /dev/null @@ -1,345 +0,0 @@ -/* - * Copyright (C) 2006 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. - */ - -// -// Zip archive entries. -// -// The ZipEntry class is tightly meshed with the ZipFile class. -// -#ifndef __LIBS_ZIPENTRY_H -#define __LIBS_ZIPENTRY_H - -#include "Errors.h" - -#include <stdlib.h> -#include <stdio.h> - -namespace android { - -class ZipFile; - -/* - * ZipEntry objects represent a single entry in a Zip archive. - * - * You can use one of these to get or set information about an entry, but - * there are no functions here for accessing the data itself. (We could - * tuck a pointer to the ZipFile in here for convenience, but that raises - * the likelihood of using ZipEntry objects after discarding the ZipFile.) - * - * File information is stored in two places: next to the file data (the Local - * File Header, and possibly a Data Descriptor), and at the end of the file - * (the Central Directory Entry). The two must be kept in sync. - */ -class ZipEntry { -public: - friend class ZipFile; - - ZipEntry(void) - : mDeleted(false), mMarked(false) - {} - ~ZipEntry(void) {} - - /* - * Returns "true" if the data is compressed. - */ - bool isCompressed(void) const { - return mCDE.mCompressionMethod != kCompressStored; - } - int getCompressionMethod(void) const { return mCDE.mCompressionMethod; } - - /* - * Return the uncompressed length. - */ - off_t getUncompressedLen(void) const { return mCDE.mUncompressedSize; } - - /* - * Return the compressed length. For uncompressed data, this returns - * the same thing as getUncompresesdLen(). - */ - off_t getCompressedLen(void) const { return mCDE.mCompressedSize; } - - /* - * Return the absolute file offset of the start of the compressed or - * uncompressed data. - */ - off_t getFileOffset(void) const { - return mCDE.mLocalHeaderRelOffset + - LocalFileHeader::kLFHLen + - mLFH.mFileNameLength + - mLFH.mExtraFieldLength; - } - - /* - * Return the data CRC. - */ - unsigned long getCRC32(void) const { return mCDE.mCRC32; } - - /* - * Return file modification time in UNIX seconds-since-epoch. - */ - time_t getModWhen(void) const; - - /* - * Return the archived file name. - */ - const char* getFileName(void) const { return (const char*) mCDE.mFileName; } - - /* - * Application-defined "mark". Can be useful when synchronizing the - * contents of an archive with contents on disk. - */ - bool getMarked(void) const { return mMarked; } - void setMarked(bool val) { mMarked = val; } - - /* - * Some basic functions for raw data manipulation. "LE" means - * Little Endian. - */ - static inline unsigned short getShortLE(const unsigned char* buf) { - return buf[0] | (buf[1] << 8); - } - static inline unsigned long getLongLE(const unsigned char* buf) { - return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24); - } - static inline void putShortLE(unsigned char* buf, short val) { - buf[0] = (unsigned char) val; - buf[1] = (unsigned char) (val >> 8); - } - static inline void putLongLE(unsigned char* buf, long val) { - buf[0] = (unsigned char) val; - buf[1] = (unsigned char) (val >> 8); - buf[2] = (unsigned char) (val >> 16); - buf[3] = (unsigned char) (val >> 24); - } - - /* defined for Zip archives */ - enum { - kCompressStored = 0, // no compression - // shrunk = 1, - // reduced 1 = 2, - // reduced 2 = 3, - // reduced 3 = 4, - // reduced 4 = 5, - // imploded = 6, - // tokenized = 7, - kCompressDeflated = 8, // standard deflate - // Deflate64 = 9, - // lib imploded = 10, - // reserved = 11, - // bzip2 = 12, - }; - - /* - * Deletion flag. If set, the entry will be removed on the next - * call to "flush". - */ - bool getDeleted(void) const { return mDeleted; } - -protected: - /* - * Initialize the structure from the file, which is pointing at - * our Central Directory entry. - */ - status_t initFromCDE(FILE* fp); - - /* - * Initialize the structure for a new file. We need the filename - * and comment so that we can properly size the LFH area. The - * filename is mandatory, the comment is optional. - */ - void initNew(const char* fileName, const char* comment); - - /* - * Initialize the structure with the contents of a ZipEntry from - * another file. - */ - status_t initFromExternal(const ZipFile* pZipFile, const ZipEntry* pEntry); - - /* - * Add some pad bytes to the LFH. We do this by adding or resizing - * the "extra" field. - */ - status_t addPadding(int padding); - - /* - * Set information about the data for this entry. - */ - void setDataInfo(long uncompLen, long compLen, unsigned long crc32, - int compressionMethod); - - /* - * Set the modification date. - */ - void setModWhen(time_t when); - - /* - * Return the offset of the local file header. - */ - off_t getLFHOffset(void) const { return mCDE.mLocalHeaderRelOffset; } - - /* - * Set the offset of the local file header, relative to the start of - * the current file. - */ - void setLFHOffset(off_t offset) { - mCDE.mLocalHeaderRelOffset = (long) offset; - } - - /* mark for deletion; used by ZipFile::remove() */ - void setDeleted(void) { mDeleted = true; } - -private: - /* these are private and not defined */ - ZipEntry(const ZipEntry& src); - ZipEntry& operator=(const ZipEntry& src); - - /* returns "true" if the CDE and the LFH agree */ - bool compareHeaders(void) const; - void copyCDEtoLFH(void); - - bool mDeleted; // set if entry is pending deletion - bool mMarked; // app-defined marker - - /* - * Every entry in the Zip archive starts off with one of these. - */ - class LocalFileHeader { - public: - LocalFileHeader(void) : - mVersionToExtract(0), - mGPBitFlag(0), - mCompressionMethod(0), - mLastModFileTime(0), - mLastModFileDate(0), - mCRC32(0), - mCompressedSize(0), - mUncompressedSize(0), - mFileNameLength(0), - mExtraFieldLength(0), - mFileName(NULL), - mExtraField(NULL) - {} - virtual ~LocalFileHeader(void) { - delete[] mFileName; - delete[] mExtraField; - } - - status_t read(FILE* fp); - status_t write(FILE* fp); - - // unsigned long mSignature; - unsigned short mVersionToExtract; - unsigned short mGPBitFlag; - unsigned short mCompressionMethod; - unsigned short mLastModFileTime; - unsigned short mLastModFileDate; - unsigned long mCRC32; - unsigned long mCompressedSize; - unsigned long mUncompressedSize; - unsigned short mFileNameLength; - unsigned short mExtraFieldLength; - unsigned char* mFileName; - unsigned char* mExtraField; - - enum { - kSignature = 0x04034b50, - kLFHLen = 30, // LocalFileHdr len, excl. var fields - }; - - void dump(void) const; - }; - - /* - * Every entry in the Zip archive has one of these in the "central - * directory" at the end of the file. - */ - class CentralDirEntry { - public: - CentralDirEntry(void) : - mVersionMadeBy(0), - mVersionToExtract(0), - mGPBitFlag(0), - mCompressionMethod(0), - mLastModFileTime(0), - mLastModFileDate(0), - mCRC32(0), - mCompressedSize(0), - mUncompressedSize(0), - mFileNameLength(0), - mExtraFieldLength(0), - mFileCommentLength(0), - mDiskNumberStart(0), - mInternalAttrs(0), - mExternalAttrs(0), - mLocalHeaderRelOffset(0), - mFileName(NULL), - mExtraField(NULL), - mFileComment(NULL) - {} - virtual ~CentralDirEntry(void) { - delete[] mFileName; - delete[] mExtraField; - delete[] mFileComment; - } - - status_t read(FILE* fp); - status_t write(FILE* fp); - - // unsigned long mSignature; - unsigned short mVersionMadeBy; - unsigned short mVersionToExtract; - unsigned short mGPBitFlag; - unsigned short mCompressionMethod; - unsigned short mLastModFileTime; - unsigned short mLastModFileDate; - unsigned long mCRC32; - unsigned long mCompressedSize; - unsigned long mUncompressedSize; - unsigned short mFileNameLength; - unsigned short mExtraFieldLength; - unsigned short mFileCommentLength; - unsigned short mDiskNumberStart; - unsigned short mInternalAttrs; - unsigned long mExternalAttrs; - unsigned long mLocalHeaderRelOffset; - unsigned char* mFileName; - unsigned char* mExtraField; - unsigned char* mFileComment; - - void dump(void) const; - - enum { - kSignature = 0x02014b50, - kCDELen = 46, // CentralDirEnt len, excl. var fields - }; - }; - - enum { - //kDataDescriptorSignature = 0x08074b50, // currently unused - kDataDescriptorLen = 16, // four 32-bit fields - - kDefaultVersion = 20, // need deflate, nothing much else - kDefaultMadeBy = 0x0317, // 03=UNIX, 17=spec v2.3 - kUsesDataDescr = 0x0008, // GPBitFlag bit 3 - }; - - LocalFileHeader mLFH; - CentralDirEntry mCDE; -}; - -}; // namespace android - -#endif // __LIBS_ZIPENTRY_H diff --git a/include/utils/ZipFile.h b/include/utils/ZipFile.h deleted file mode 100644 index 44df5bb..0000000 --- a/include/utils/ZipFile.h +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (C) 2006 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. - */ - -// -// General-purpose Zip archive access. This class allows both reading and -// writing to Zip archives, including deletion of existing entries. -// -#ifndef __LIBS_ZIPFILE_H -#define __LIBS_ZIPFILE_H - -#include "ZipEntry.h" -#include "Vector.h" -#include "Errors.h" -#include <stdio.h> - -namespace android { - -/* - * Manipulate a Zip archive. - * - * Some changes will not be visible in the until until "flush" is called. - * - * The correct way to update a file archive is to make all changes to a - * copy of the archive in a temporary file, and then unlink/rename over - * the original after everything completes. Because we're only interested - * in using this for packaging, we don't worry about such things. Crashing - * after making changes and before flush() completes could leave us with - * an unusable Zip archive. - */ -class ZipFile { -public: - ZipFile(void) - : mZipFp(NULL), mReadOnly(false), mNeedCDRewrite(false) - {} - ~ZipFile(void) { - if (!mReadOnly) - flush(); - if (mZipFp != NULL) - fclose(mZipFp); - discardEntries(); - } - - /* - * Open a new or existing archive. - */ - typedef enum { - kOpenReadOnly = 0x01, - kOpenReadWrite = 0x02, - kOpenCreate = 0x04, // create if it doesn't exist - kOpenTruncate = 0x08, // if it exists, empty it - }; - status_t open(const char* zipFileName, int flags); - - /* - * Add a file to the end of the archive. Specify whether you want the - * library to try to store it compressed. - * - * If "storageName" is specified, the archive will use that instead - * of "fileName". - * - * If there is already an entry with the same name, the call fails. - * Existing entries with the same name must be removed first. - * - * If "ppEntry" is non-NULL, a pointer to the new entry will be returned. - */ - status_t add(const char* fileName, int compressionMethod, - ZipEntry** ppEntry) - { - return add(fileName, fileName, compressionMethod, ppEntry); - } - status_t add(const char* fileName, const char* storageName, - int compressionMethod, ZipEntry** ppEntry) - { - return addCommon(fileName, NULL, 0, storageName, - ZipEntry::kCompressStored, - compressionMethod, ppEntry); - } - - /* - * Add a file that is already compressed with gzip. - * - * If "ppEntry" is non-NULL, a pointer to the new entry will be returned. - */ - status_t addGzip(const char* fileName, const char* storageName, - ZipEntry** ppEntry) - { - return addCommon(fileName, NULL, 0, storageName, - ZipEntry::kCompressDeflated, - ZipEntry::kCompressDeflated, ppEntry); - } - - /* - * Add a file from an in-memory data buffer. - * - * If "ppEntry" is non-NULL, a pointer to the new entry will be returned. - */ - status_t add(const void* data, size_t size, const char* storageName, - int compressionMethod, ZipEntry** ppEntry) - { - return addCommon(NULL, data, size, storageName, - ZipEntry::kCompressStored, - compressionMethod, ppEntry); - } - - /* - * Add an entry by copying it from another zip file. If "padding" is - * nonzero, the specified number of bytes will be added to the "extra" - * field in the header. - * - * If "ppEntry" is non-NULL, a pointer to the new entry will be returned. - */ - status_t add(const ZipFile* pSourceZip, const ZipEntry* pSourceEntry, - int padding, ZipEntry** ppEntry); - - /* - * Mark an entry as having been removed. It is not actually deleted - * from the archive or our internal data structures until flush() is - * called. - */ - status_t remove(ZipEntry* pEntry); - - /* - * Flush changes. If mNeedCDRewrite is set, this writes the central dir. - */ - status_t flush(void); - - /* - * Expand the data into the buffer provided. The buffer must hold - * at least <uncompressed len> bytes. Variation expands directly - * to a file. - * - * Returns "false" if an error was encountered in the compressed data. - */ - //bool uncompress(const ZipEntry* pEntry, void* buf) const; - //bool uncompress(const ZipEntry* pEntry, FILE* fp) const; - void* uncompress(const ZipEntry* pEntry); - - /* - * Get an entry, by name. Returns NULL if not found. - * - * Does not return entries pending deletion. - */ - ZipEntry* getEntryByName(const char* fileName) const; - - /* - * Get the Nth entry in the archive. - * - * This will return an entry that is pending deletion. - */ - int getNumEntries(void) const { return mEntries.size(); } - ZipEntry* getEntryByIndex(int idx) const; - -private: - /* these are private and not defined */ - ZipFile(const ZipFile& src); - ZipFile& operator=(const ZipFile& src); - - class EndOfCentralDir { - public: - EndOfCentralDir(void) : - mDiskNumber(0), - mDiskWithCentralDir(0), - mNumEntries(0), - mTotalNumEntries(0), - mCentralDirSize(0), - mCentralDirOffset(0), - mCommentLen(0), - mComment(NULL) - {} - virtual ~EndOfCentralDir(void) { - delete[] mComment; - } - - status_t readBuf(const unsigned char* buf, int len); - status_t write(FILE* fp); - - //unsigned long mSignature; - unsigned short mDiskNumber; - unsigned short mDiskWithCentralDir; - unsigned short mNumEntries; - unsigned short mTotalNumEntries; - unsigned long mCentralDirSize; - unsigned long mCentralDirOffset; // offset from first disk - unsigned short mCommentLen; - unsigned char* mComment; - - enum { - kSignature = 0x06054b50, - kEOCDLen = 22, // EndOfCentralDir len, excl. comment - - kMaxCommentLen = 65535, // longest possible in ushort - kMaxEOCDSearch = kMaxCommentLen + EndOfCentralDir::kEOCDLen, - - }; - - void dump(void) const; - }; - - - /* read all entries in the central dir */ - status_t readCentralDir(void); - - /* crunch deleted entries out */ - status_t crunchArchive(void); - - /* clean up mEntries */ - void discardEntries(void); - - /* common handler for all "add" functions */ - status_t addCommon(const char* fileName, const void* data, size_t size, - const char* storageName, int sourceType, int compressionMethod, - ZipEntry** ppEntry); - - /* copy all of "srcFp" into "dstFp" */ - status_t copyFpToFp(FILE* dstFp, FILE* srcFp, unsigned long* pCRC32); - /* copy all of "data" into "dstFp" */ - status_t copyDataToFp(FILE* dstFp, - const void* data, size_t size, unsigned long* pCRC32); - /* copy some of "srcFp" into "dstFp" */ - status_t copyPartialFpToFp(FILE* dstFp, FILE* srcFp, long length, - unsigned long* pCRC32); - /* like memmove(), but on parts of a single file */ - status_t filemove(FILE* fp, off_t dest, off_t src, size_t n); - /* compress all of "srcFp" into "dstFp", using Deflate */ - status_t compressFpToFp(FILE* dstFp, FILE* srcFp, - const void* data, size_t size, unsigned long* pCRC32); - - /* get modification date from a file descriptor */ - time_t getModTime(int fd); - - /* - * We use stdio FILE*, which gives us buffering but makes dealing - * with files >2GB awkward. Until we support Zip64, we're fine. - */ - FILE* mZipFp; // Zip file pointer - - /* one of these per file */ - EndOfCentralDir mEOCD; - - /* did we open this read-only? */ - bool mReadOnly; - - /* set this when we trash the central dir */ - bool mNeedCDRewrite; - - /* - * One ZipEntry per entry in the zip file. I'm using pointers instead - * of objects because it's easier than making operator= work for the - * classes and sub-classes. - */ - Vector<ZipEntry*> mEntries; -}; - -}; // namespace android - -#endif // __LIBS_ZIPFILE_H diff --git a/include/utils/executablepath.h b/include/utils/executablepath.h deleted file mode 100644 index c979432..0000000 --- a/include/utils/executablepath.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2008 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 _UTILS_EXECUTABLEPATH_H -#define _UTILS_EXECUTABLEPATH_H - -#include <limits.h> - -// returns the path to this executable -#if __cplusplus -extern "C" -#endif -void executablepath(char s[PATH_MAX]); - -#endif // _UTILS_EXECUTABLEPATH_H diff --git a/include/utils/inet_address.h b/include/utils/inet_address.h deleted file mode 100644 index dbd8672..0000000 --- a/include/utils/inet_address.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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. - */ - -// -// Internet address classes. Modeled after Java classes. -// -#ifndef _RUNTIME_INET_ADDRESS_H -#define _RUNTIME_INET_ADDRESS_H - -#ifdef HAVE_ANDROID_OS -#error DO NOT USE THIS FILE IN THE DEVICE BUILD -#endif - - -namespace android { - -/* - * This class holds Internet addresses. Perhaps more useful is its - * ability to look up addresses by name. - * - * Invoke one of the static factory methods to create a new object. - */ -class InetAddress { -public: - virtual ~InetAddress(void); - - // create from w.x.y.z or foo.bar.com notation - static InetAddress* getByName(const char* host); - - // copy-construction - InetAddress(const InetAddress& orig); - - const void* getAddress(void) const { return mAddress; } - int getAddressLength(void) const { return mLength; } - const char* getHostName(void) const { return mName; } - -private: - InetAddress(void); - // assignment (private) - InetAddress& operator=(const InetAddress& addr); - - // use a void* here so we don't have to expose actual socket headers - void* mAddress; // this is really a ptr to sockaddr_in - int mLength; - char* mName; -}; - - -/* - * Base class for socket addresses. - */ -class SocketAddress { -public: - SocketAddress() {} - virtual ~SocketAddress() {} -}; - - -/* - * Internet address class. This combines an InetAddress with a port. - */ -class InetSocketAddress : public SocketAddress { -public: - InetSocketAddress() : - mAddress(0), mPort(-1) - {} - ~InetSocketAddress(void) { - delete mAddress; - } - - // Create an address with a host wildcard (useful for servers). - bool create(int port); - // Create an address with the specified host and port. - bool create(const InetAddress* addr, int port); - // Create an address with the specified host and port. Does the - // hostname lookup. - bool create(const char* host, int port); - - const InetAddress* getAddress(void) const { return mAddress; } - const int getPort(void) const { return mPort; } - const char* getHostName(void) const { return mAddress->getHostName(); } - -private: - InetAddress* mAddress; - int mPort; -}; - -}; // namespace android - -#endif // _RUNTIME_INET_ADDRESS_H diff --git a/include/utils/misc.h b/include/utils/misc.h index 62e84b4..23f2a4c 100644 --- a/include/utils/misc.h +++ b/include/utils/misc.h @@ -21,7 +21,7 @@ #define _LIBS_UTILS_MISC_H #include <sys/time.h> -#include "utils/Endian.h" +#include <utils/Endian.h> namespace android { diff --git a/include/utils/ported.h b/include/utils/ported.h deleted file mode 100644 index eb3be01..0000000 --- a/include/utils/ported.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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. - */ - -// -// Standard functions ported to the current platform. Note these are NOT -// in the "android" namespace. -// -#ifndef _LIBS_UTILS_PORTED_H -#define _LIBS_UTILS_PORTED_H - -#include <sys/time.h> // for timeval - -#ifdef __cplusplus -extern "C" { -#endif - -/* library replacement functions */ -#if defined(NEED_GETTIMEOFDAY) -int gettimeofday(struct timeval* tv, struct timezone* tz); -#endif -#if defined(NEED_USLEEP) -void usleep(unsigned long usec); -#endif -#if defined(NEED_PIPE) -int pipe(int filedes[2]); -#endif -#if defined(NEED_SETENV) -int setenv(const char* name, const char* value, int overwrite); -void unsetenv(const char* name); -char* getenv(const char* name); -#endif - -#ifdef __cplusplus -} -#endif - -#endif // _LIBS_UTILS_PORTED_H diff --git a/include/utils/string_array.h b/include/utils/string_array.h deleted file mode 100644 index 064dda2..0000000 --- a/include/utils/string_array.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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. - */ - -// -// Sortable array of strings. STL-ish, but STL-free. -// -#ifndef _LIBS_UTILS_STRING_ARRAY_H -#define _LIBS_UTILS_STRING_ARRAY_H - -#include <stdlib.h> -#include <string.h> - -namespace android { - -// -// An expanding array of strings. Add, get, sort, delete. -// -class StringArray { -public: - StringArray() - : mMax(0), mCurrent(0), mArray(NULL) - {} - virtual ~StringArray() { - for (int i = 0; i < mCurrent; i++) - delete[] mArray[i]; - delete[] mArray; - } - - // - // Add a string. A copy of the string is made. - // - bool push_back(const char* str) { - if (mCurrent >= mMax) { - char** tmp; - - if (mMax == 0) - mMax = 16; // initial storage - else - mMax *= 2; - - tmp = new char*[mMax]; - if (tmp == NULL) - return false; - - memcpy(tmp, mArray, mCurrent * sizeof(char*)); - delete[] mArray; - mArray = tmp; - } - - int len = strlen(str); - mArray[mCurrent] = new char[len+1]; - memcpy(mArray[mCurrent], str, len+1); - mCurrent++; - - return true; - } - - // - // Delete an entry. - // - void erase(int idx) { - if (idx < 0 || idx >= mCurrent) - return; - delete[] mArray[idx]; - if (idx < mCurrent-1) { - memmove(&mArray[idx], &mArray[idx+1], - (mCurrent-1 - idx) * sizeof(char*)); - } - mCurrent--; - } - - // - // Sort the array. - // - void sort(int (*compare)(const void*, const void*)) { - qsort(mArray, mCurrent, sizeof(char*), compare); - } - - // - // Pass this to the sort routine to do an ascending alphabetical sort. - // - static int cmpAscendingAlpha(const void* pstr1, const void* pstr2) { - return strcmp(*(const char**)pstr1, *(const char**)pstr2); - } - - // - // Get the #of items in the array. - // - inline int size(void) const { return mCurrent; } - - // - // Return entry N. - // [should use operator[] here] - // - const char* getEntry(int idx) const { - if (idx < 0 || idx >= mCurrent) - return NULL; - return mArray[idx]; - } - - // - // Set entry N to specified string. - // [should use operator[] here] - // - void setEntry(int idx, const char* str) { - if (idx < 0 || idx >= mCurrent) - return; - delete[] mArray[idx]; - int len = strlen(str); - mArray[idx] = new char[len+1]; - memcpy(mArray[idx], str, len+1); - } - -private: - int mMax; - int mCurrent; - char** mArray; -}; - -}; // namespace android - -#endif // _LIBS_UTILS_STRING_ARRAY_H diff --git a/include/utils/threads.h b/include/utils/threads.h index b320915..e9b0788 100644 --- a/include/utils/threads.h +++ b/include/utils/threads.h @@ -21,6 +21,10 @@ #include <sys/types.h> #include <time.h> +#if defined(HAVE_PTHREADS) +# include <pthread.h> +#endif + // ------------------------------------------------------------------ // C API @@ -176,6 +180,8 @@ inline thread_id_t getThreadId() { return androidGetThreadId(); } +/*****************************************************************************/ + /* * Simple mutex class. The implementation is system-dependent. * @@ -184,8 +190,14 @@ inline thread_id_t getThreadId() { */ class Mutex { public: + enum { + NORMAL = 0, + SHARED = 1 + }; + Mutex(); Mutex(const char* name); + Mutex(int type, const char* name = NULL); ~Mutex(); // lock or unlock the mutex @@ -199,11 +211,11 @@ public: // constructed and released when Autolock goes out of scope. class Autolock { public: - inline Autolock(Mutex& mutex) : mpMutex(&mutex) { mutex.lock(); } - inline Autolock(Mutex* mutex) : mpMutex(mutex) { mutex->lock(); } - inline ~Autolock() { mpMutex->unlock(); } + inline Autolock(Mutex& mutex) : mLock(mutex) { mLock.lock(); } + inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); } + inline ~Autolock() { mLock.unlock(); } private: - Mutex* mpMutex; + Mutex& mLock; }; private: @@ -212,11 +224,49 @@ private: // A mutex cannot be copied Mutex(const Mutex&); Mutex& operator = (const Mutex&); - void _init(); +#if defined(HAVE_PTHREADS) + pthread_mutex_t mMutex; +#else + void _init(); void* mState; +#endif }; +#if defined(HAVE_PTHREADS) + +inline Mutex::Mutex() { + pthread_mutex_init(&mMutex, NULL); +} +inline Mutex::Mutex(const char* name) { + pthread_mutex_init(&mMutex, NULL); +} +inline Mutex::Mutex(int type, const char* name) { + if (type == SHARED) { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); + pthread_mutex_init(&mMutex, &attr); + pthread_mutexattr_destroy(&attr); + } else { + pthread_mutex_init(&mMutex, NULL); + } +} +inline Mutex::~Mutex() { + pthread_mutex_destroy(&mMutex); +} +inline status_t Mutex::lock() { + return -pthread_mutex_lock(&mMutex); +} +inline void Mutex::unlock() { + pthread_mutex_unlock(&mMutex); +} +inline status_t Mutex::tryLock() { + return -pthread_mutex_trylock(&mMutex); +} + +#endif // HAVE_PTHREADS + /* * Automatic mutex. Declare one of these at the top of a function. * When the function returns, it will go out of scope, and release the @@ -225,6 +275,7 @@ private: typedef Mutex::Autolock AutoMutex; +/*****************************************************************************/ /* * Condition variable class. The implementation is system-dependent. @@ -240,9 +291,6 @@ public: ~Condition(); // Wait on the condition variable. Lock the mutex before calling. status_t wait(Mutex& mutex); - // Wait on the condition variable until the given time. Lock the mutex - // before calling. - status_t wait(Mutex& mutex, nsecs_t abstime); // same with relative timeout status_t waitRelative(Mutex& mutex, nsecs_t reltime); // Signal the condition variable, allowing one thread to continue. @@ -251,9 +299,60 @@ public: void broadcast(); private: +#if defined(HAVE_PTHREADS) + pthread_cond_t mCond; +#else void* mState; +#endif }; +#if defined(HAVE_PTHREADS) + +inline Condition::Condition() { + pthread_cond_init(&mCond, NULL); +} +inline Condition::~Condition() { + pthread_cond_destroy(&mCond); +} +inline status_t Condition::wait(Mutex& mutex) { + return -pthread_cond_wait(&mCond, &mutex.mMutex); +} +inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) { +#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE) + struct timespec ts; + ts.tv_sec = reltime/1000000000; + ts.tv_nsec = reltime%1000000000; + return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts); +#else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE + struct timespec ts; +#if defined(HAVE_POSIX_CLOCKS) + clock_gettime(CLOCK_REALTIME, &ts); +#else // HAVE_POSIX_CLOCKS + // we don't support the clocks here. + struct timeval t; + gettimeofday(&t, NULL); + ts.tv_sec = t.tv_sec; + ts.tv_nsec= t.tv_usec*1000; +#endif // HAVE_POSIX_CLOCKS + ts.tv_sec += reltime/1000000000; + ts.tv_nsec+= reltime%1000000000; + if (ts.tv_nsec >= 1000000000) { + ts.tv_nsec -= 1000000000; + ts.tv_sec += 1; + } + return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts); +#endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE +} +inline void Condition::signal() { + pthread_cond_signal(&mCond); +} +inline void Condition::broadcast() { + pthread_cond_broadcast(&mCond); +} + +#endif // HAVE_PTHREADS + +/*****************************************************************************/ /* * This is our spiffy thread object! @@ -291,7 +390,7 @@ protected: bool exitPending() const; private: - // Derived class must implemtent threadLoop(). The thread starts its life + // Derived class must implement threadLoop(). The thread starts its life // here. There are two ways of using the Thread object: // 1) loop: if threadLoop() returns true, it will be called again if // requestExit() wasn't called. |