Android native development: system/core/libutils

1. AndroidThreads.h

Encapsulates thread-related functions, such as creating, setting priority, setting name, etc. Provide c and c + + interface.

// c interfaces
extern int androidCreateThread(android_thread_func_t, void *);
extern int androidCreateThreadEtc(android_thread_func_t entryFunction,
                                  void *userData,
                                  const char* threadName,
                                  int32_t threadPriority,
                                  size_t threadStackSize,
                                  android_thread_id_t *threadId);
extern android_thread_id_t androidGetThreadId();
extern int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
                                     void *userData,
                                     const char* threadName,
                                     int32_t threadPriority,
                                     size_t threadStackSize,
                                     android_thread_id_t *threadId);
extern void androidSetThreadName(const char* name);
typedef int (*android_create_thread_fn)(android_thread_func_t entryFunction,
                                        void *userData,
                                        const char* threadName,
                                        int32_t threadPriority,
                                        size_t threadStackSize,
                                        android_thread_id_t *threadId);

extern void androidSetCreateThreadFunc(android_create_thread_fn func);

extern int androidSetThreadPriority(pid_t tid, int prio);
extern int androidGetThreadPriority(pid_t tid);

// cpp interfaces
inline bool createThread(thread_func_t f, void *a)
inline bool createThreadEtc(thread_func_t entryFunction,
                            void *userData,
                            const char* threadName = "android:unnamed_thread",
                            int32_t threadPriority = PRIORITY_DEFAULT,
                            size_t threadStackSize = 0,
                            thread_id_t *threadId = nullptr)
inline thread_id_t getThreadId()

2. Atomic.h

#include <cutils/atomic.h>

3. BitSet.h

Bit manipulation helper functions.

DO NOT USE: std::bitset<32> or std::bitset<64> preferred

4. ByteOrder.h

See: <android-base/endian.h>
system/core/base library introduction

5. CallStack.h

Collect and print a thread's callstack.
Reference: ProcessCallStack.h, collect all thread callstack in a process.

class CallStack {
    
    
public:
    CallStack();
    CallStack(const char* logtag, int32_t ignoreDepth = 1);
    ~CallStack();

    void clear() {
    
     mFrameLines.clear(); }
    void update(int32_t ignoreDepth = 1, pid_t tid = BACKTRACE_CURRENT_THREAD);
    void log(const char* logtag,
             android_LogPriority priority = ANDROID_LOG_DEBUG,
             const char* prefix = nullptr) const;
    void dump(int fd, int indent = 0, const char* prefix = nullptr) const;
    String8 toString(const char* prefix = nullptr) const;
    void print(Printer& printer) const;
    size_t size() const {
    
     return mFrameLines.size(); }
}

6. Compat.h

There is no off64_t on Mac os, the default off_t is 64 bits. compatibility adaptation.

/* Mac OS has always had a 64-bit off_t, so it doesn't have off64_t. */
typedef off_t off64_t;

static inline off64_t lseek64(int fd, off64_t offset, int whence) {
    
    
    return lseek(fd, offset, whence);
}

static inline int ftruncate64(int fd, off64_t length) {
    
    
    return ftruncate(fd, length);
}

static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset)static inline ssize_t pwrite64(int fd, const void* buf, size_t nbytes, off64_t offset)static inline void* mmap64(void* addr, size_t length, int prot, int flags, int fd, off64_t offset)

7. Condition.h

// DO NOT USE: please use std::condition_variable instead.

8. Debug.h

CompileTimeAssert macro, legacy code.
// DO NOT USE: Please use static_assert instead

#ifdef __cplusplus
template<bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {
    
    };
#define COMPILE_TIME_ASSERT(_exp) \
    template class CompileTimeAssert< (_exp) >;
#endif

// DO NOT USE: Please use static_assert instead
#define COMPILE_TIME_ASSERT_FUNCTION_SCOPE(_exp) \
    CompileTimeAssert<( _exp )>();

9. Endian.h

#include <endian.h>

10. Errors.h

Define the error code in Android, corresponding to Linux or Win32.

enum {
    
    
    OK                = 0,    // Preferred constant for checking success.
    NO_ERROR          = OK,   // Deprecated synonym for `OK`. Prefer `OK` because it doesn't conflict with Windows.

    UNKNOWN_ERROR       = (-2147483647-1), // INT32_MIN value

    NO_MEMORY           = -ENOMEM,
    INVALID_OPERATION   = -ENOSYS,
    BAD_VALUE           = -EINVAL,
	// 还有若干error code...
}

std::string statusToString(status_t status);

std::string statusToString(status_t s) {
    
    
#define STATUS_CASE(STATUS) \
    case STATUS:            \
        return #STATUS

    switch (s) {
    
    
        STATUS_CASE(OK);
        STATUS_CASE(UNKNOWN_ERROR);
        ...
#undef STATUS_CASE
    }

    return std::to_string(s) + " (" + strerror(-s) + ")";
}

11. FastStrcmp.h

A template function optimized for the strcpm function.

// Usage is of the form:
//  fastcmp<strncmp>(str1, str2, len)

template <int (*cmp)(const char* l, const char* r, const size_t s)>
static inline int fastcmp(const char* l, const char* r, const size_t s);

template <int (*cmp)(const char* l, const char* r, const size_t s)>
static inline int fasticmp(const char* l, const char* r, const size_t s);

template <int (*cmp)(const void* l, const void* r, const size_t s)>
static inline int fastcmp(const void* lv, const void* rv, const size_t s);

template <int (*cmp)(const char* l, const char* r)>
static inline int fastcmp(const char* l, const char* r) {
    
    
    return (*l != *r) || (__predict_true(*l) && cmp(l + 1, r + 1));
}

template <int (*cmp)(const char* l, const char* r)>
static inline int fasticmp(const char* l, const char* r) {
    
    
    return (tolower(*l) != tolower(*r)) || (__predict_true(*l) && cmp(l + 1, r + 1));
}

12. FileMap.h

Encapsulation of memory-mapped files (mmap64, munmap), which can map the entire file or part of the file.

class FileMap {
    
    
public:
    FileMap(void);

    FileMap(FileMap&& f) noexcept;
    FileMap& operator=(FileMap&& f) noexcept;

    bool create(const char* origFileName, int fd,
                off64_t offset, size_t length, bool readOnly);
    ~FileMap(void);

    const char* getFileName(void) const {
    
     return mFileName; }
    void* getDataPtr(void) const {
    
     return mDataPtr; }
    size_t getDataLength(void) const {
    
     return mDataLength; }
    off64_t getDataOffset(void) const {
    
     return mDataOffset; }
    int advise(MapAdvice advice);
}

13. Flattenable.h

// DO NOT USE: please use parcelable instead
// This code is deprecated and will not be supported via AIDL code gen. For data
// to be sent over binder, please use parcelables.

14. Functor.h

Custom Functors.

// DO NOT USE: please use
// - C++ lambda
// - class with well-defined and specific functionality and semantics

15. JenkinsHash.h

Several hash functions.

inline uint32_t JenkinsHashMix(uint32_t hash, uint32_t data);
hash_t JenkinsHashWhiten(uint32_t hash);
uint32_t JenkinsHashMixBytes(uint32_t hash, const uint8_t* bytes, size_t size);
uint32_t JenkinsHashMixShorts(uint32_t hash, const uint16_t* shorts, size_t size);

16. KeyedVector.h

DO NOT USE: please use std::map

17. LightRefBase.h

参见:28. RefBase.h

18. List.h

DO NOT USE: please use std::list
to customize the doubly linked list.

19. Log.h

#include <log/log.h>

20. Looper.h

ALL

21. LruCache.h

A template class that implements LruCache.

class LruCache {
    
    
public:
    explicit LruCache(uint32_t maxCapacity);
    virtual ~LruCache();

    void setOnEntryRemovedListener(OnEntryRemoved<TKey, TValue>* listener);
    size_t size() const;
    const TValue& get(const TKey& key);
    bool put(const TKey& key, const TValue& value);
    bool remove(const TKey& key);
    bool removeOldest();
    void clear();
    const TValue& peekOldestValue();
}

22. misc.h

System property registration listener and change notification function.

typedef void (*sysprop_change_callback)(void);
void add_sysprop_change_callback(sysprop_change_callback cb, int priority);
void report_sysprop_change();

23. Mutex.h

Some thread related attribute macros.
A Mutex used on the Win32 platform.

#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
#define ACQUIRED_BEFORE(...) THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
#define ACQUIRED_AFTER(...) THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))

24. NativeHandle.h

The encapsulation <cutils/native_handle.h>class of native_handle_t.

class NativeHandle : public LightRefBase<NativeHandle> {
    
    
public:
    static sp<NativeHandle> create(native_handle_t* handle, bool ownsHandle);
    const native_handle_t* handle() const}

25. Printer.h

An auxiliary class for outputting data streams, which can output to logcat, files, strings, and add prefixes to other Printers.

// Interface for printing to an arbitrary data stream
class Printer {
    
    
public:
    virtual void printLine(const char* string = "") = 0;
    virtual void printFormatLine(const char* format, ...) __attribute__((format (printf, 2, 3)));
}; // class Printer

// Print to logcat
class LogPrinter : public Printer {
    
    
public:
    LogPrinter(const char* logtag,
               android_LogPriority priority = ANDROID_LOG_DEBUG,
               const char* prefix = nullptr,
               bool ignoreBlankLines = false);

    virtual void printLine(const char* string);
}; // class LogPrinter

// Print to a file descriptor
class FdPrinter : public Printer {
    
    
public:
    FdPrinter(int fd, unsigned int indent = 0, const char* prefix = nullptr);
    virtual void printLine(const char* string);
}; // class FdPrinter

// Print to a String8
class String8Printer : public Printer {
    
    
public:
    String8Printer(String8* target, const char* prefix = nullptr);
    virtual void printLine(const char* string);
}; // class String8Printer

// Print to an existing Printer by adding a prefix to each line
class PrefixPrinter : public Printer {
    
    
public:
    PrefixPrinter(Printer& printer, const char* prefix);
    virtual void printLine(const char* string);
};

26. ProcessCallStack.h

Collect and print stack traces of all threads in a process.
Reference: CallStack.h

class ProcessCallStack {
    
    
public:
    ProcessCallStack();
    ProcessCallStack(const ProcessCallStack& rhs);
    ~ProcessCallStack();

    void update();
    void log(const char* logtag, android_LogPriority priority = ANDROID_LOG_DEBUG,
             const char* prefix = nullptr) const;
    void dump(int fd, int indent = 0, const char* prefix = nullptr) const;
    String8 toString(const char* prefix = nullptr) const;
    void print(Printer& printer) const;
    size_t size() const;
}

27. PropertyMap.h

Operations on property files (analysis, addition and modification, etc.), file content:
property1 = value1
property2 = value2

28. RefBase.h

 LightRefBase.h
 StrongPointer.h

Several related classes are put together.
1) File content organization:
(1) RefBase.h contains class RefBase, class weakref_type (RefBase internal class), template class wp definition.
(2) The weakref_type derived class weakref_impl is defined in RefBase.cpp, weakref_type only defines some interfaces, and weakref_impl is the implementation class.
2) Class functions and dependencies:
(1) class RefBase, strong reference base class, defines incStrong, decStrong and other interfaces, which can be used in template class sp. By inheriting RefBase, the derivation is endowed with strong ref related functions.
(2) class weakref_type, weak reference base class, defines incWeak, decWeak and other interfaces, which can be used in template class wp.
(3) class weakref_impl implements some debugging-related functions. If the debugging macro switch is not turned on, the function is consistent with weakref_type.
(4) template class wp, weak pointer template class, defined in RefBase.h.
(5) template class sp, strong pointer template class, defined in StrongPointer.h.
wp and sp are smart pointers with reference counts (strong references and weak references, respectively).
(6) LightRefBase (derived template class VirtualLightRefBase) is a simplified implementation of RefBase.
(7) Both RefBase and weakref_type have member methods that can be converted to each other.
(8) On the basis of strong references and weak references, the extendObjectLifetime() method can be called to extend the life cycle of the object.
There are many applications in Binder implementation.

// RefBase.h
class RefBase
{
    
    
public:
            void            incStrong(const void* id) const;
            void            decStrong(const void* id) const;
            void            forceIncStrong(const void* id) const;

    class weakref_type
    {
    
    
    public:
        RefBase*            refBase() const;

        void                incWeak(const void* id);
        void                decWeak(const void* id);
        bool                attemptIncStrong(const void* id);
        bool                attemptIncWeak(const void* id);
    };
            weakref_type*   createWeak(const void* id) const;
            weakref_type*   getWeakRefs() const;

protected:
                            RefBase();
    virtual                 ~RefBase();
    void            extendObjectLifetime(int32_t mode);

    virtual void            onFirstRef();
    virtual void            onLastStrongRef(const void* id);
    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
    virtual void            onLastWeakRef(const void* id);

private:
    friend class weakref_type;
    class weakref_impl;
    weakref_impl* const mRefs;
};

template <typename T>
class wp
{
    
    
public:
    typedef typename RefBase::weakref_type weakref_type;

    wp(T* other);  // NOLINT(implicit)
    ~wp();
	// 构造、赋值构造、移动构造以及操作符定义,省略

    void set_object_and_refs(T* other, weakref_type* refs);
    sp<T> promote() const;
    void clear();
    inline  weakref_type* get_refs() const {
    
     return m_refs; }
    inline  T* unsafe_get() const {
    
     return m_ptr; }
    // 各种比较操作符,省略
    
private:
    template<typename Y> friend class sp;
    template<typename Y> friend class wp;

    T*              m_ptr;
    weakref_type*   m_refs;
};

// StrongPointer.h ---------------------------------------------------------------------
template<typename T>
class sp {
    
    
public:
    sp(T* other);  // NOLINT(implicit)
    ~sp();
	// 构造、赋值构造、移动构造以及操作符定义,省略

    //! Special optimization for use by ProcessState (and nobody else).
    void force_set(T* other);
    void clear();

    inline T&       operator* () const     {
    
     return *m_ptr; }
    inline T*       operator-> () const    {
    
     return m_ptr;  }
    inline T*       get() const            {
    
     return m_ptr; }
    inline explicit operator bool () const {
    
     return m_ptr != nullptr; }

	// 内部仅定义==和!=,外部函数定义了包括==,!=等全部比较运算符。
    template<typename U>
    inline bool operator == (const wp<U>& o) const {
    
    
        return o == *this;
    }
    template<typename U>
    inline bool operator != (const wp<U>& o) const {
    
    
        return o != *this;
    }

private:
    template<typename Y> friend class sp;
    template<typename Y> friend class wp;
    void set_pointer(T* ptr);
    T* m_ptr;
};

// LightRefBase.h ---------------------------------------------------------------------
template <class T>
class LightRefBase
{
    
    
public:
    inline LightRefBase();
    inline void incStrong(__attribute__((unused)) const void* id) const;
    inline void decStrong(__attribute__((unused)) const void* id) const;
private:
    mutable std::atomic<int32_t> mCount;
};


// This is a wrapper around LightRefBase that simply enforces a virtual
// destructor to eliminate the template requirement of LightRefBase
class VirtualLightRefBase : public LightRefBase<VirtualLightRefBase> {
    
    
public:
    virtual ~VirtualLightRefBase() = default;
};

29. RWLock.h

mutex implementation, RWLock/AutoRLock/AutoWLock, probably legacy code.

30. Singleton.h

// DO NOT USE: Please use scoped static initialization. For instance:
//     MyClass& getInstance() {
    
    
//         static MyClass gInstance(...);
//         return gInstance;
//     }

31. SortedVector.h

// DO NOT USE: please use std::set

32. StopWatch.h

A custom StopWatch, get the time and call systemTime();

class StopWatch
{
    
    
public:
  StopWatch(const char* name, int clock = SYSTEM_TIME_MONOTONIC);
  ~StopWatch();

  const char* name() const;
  nsecs_t lap();
  nsecs_t elapsedTime() const;

  void reset();
}

33. String16.h

// DO NOT USE: please use std::u16string

34. String8.h

// DO NOT USE: please use std::string

35. StrongPointer.h

参见:28. RefBase.h

36. SystemClock.h

Call clock_gettime(CLOCK_BOOTTIME, &ts); to get the system startup time.

int64_t uptimeMillis();
int64_t elapsedRealtime();
int64_t elapsedRealtimeNano();

37. ThreadDefs.h

Some thread-related type definitions (such as: thread_id_t, thread_func_t) and priority enum definitions.

38. Thread.h

// DO NOT USE: please use std::thread

39. threads.h

#include <utils/AndroidThreads.h>

#include <utils/Condition.h>
#include <utils/Errors.h>
#include <utils/Mutex.h>
#include <utils/RWLock.h>
#include <utils/Thread.h>

40. Timers.h

Get the system time, and some conversion methods of different unit time.

enum {
    
    
    SYSTEM_TIME_REALTIME = 0,  // system-wide realtime clock
    SYSTEM_TIME_MONOTONIC = 1, // monotonic time since unspecified starting point
    SYSTEM_TIME_PROCESS = 2,   // high-resolution per-process clock
    SYSTEM_TIME_THREAD = 3,    // high-resolution per-thread clock
    SYSTEM_TIME_BOOTTIME = 4   // same as SYSTEM_TIME_MONOTONIC, but including CPU suspend time
};

// return the system-time according to the specified clock
nsecs_t systemTime(int clock);
int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime);

41. Tokenizer.h

Read a text file line by line and parse it into words (tokens).

42. Trace.h

Trace auxiliary function, automatically starts and stops in the scope, calls atrace_begin in the constructor, and calls atrace_end in the destructor.
Used in conjunction with the method in <cutils/trace.h>.

class ScopedTrace {
    
    
public:
    inline ScopedTrace(uint64_t tag, const char* name) : mTag(tag) {
    
    
        atrace_begin(mTag, name);
    }

    inline ~ScopedTrace() {
    
    
        atrace_end(mTag);
    }
};

43. TypeHelpers.h

Some custom type traits should be an early supplement to C++.
Assist the following custom Vector implementation.

44. Unicode.h

Auxiliary functions, including char16_t, char32_t comparison, and length acquisition.
And utf8, utf16, utf32 conversion and other functions.

int strcmp16(const char16_t *, const char16_t *);
int strncmp16(const char16_t *s1, const char16_t *s2, size_t n);
size_t strlen16(const char16_t *);
size_t strnlen16(const char16_t *, size_t);
char16_t *strcpy16(char16_t *, const char16_t *);
char16_t *strstr16(const char16_t*, const char16_t*);
int strzcmp16(const char16_t *s1, size_t n1, const char16_t *s2, size_t n2);

size_t strlen32(const char32_t *);
size_t strnlen32(const char32_t *, size_t);

ssize_t utf32_to_utf8_length(const char32_t *src, size_t src_len);
void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len);
int32_t utf32_from_utf8_at(const char *src, size_t src_len, size_t index, size_t *next_index);

ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len);
void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len);

ssize_t utf8_to_utf16_length(const uint8_t* src, size_t srcLen, bool overreadIsFatal = false);
char16_t* utf8_to_utf16_no_null_terminator(const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen);
char16_t *utf8_to_utf16(const uint8_t* src, size_t srcLen, char16_t* dst, size_t dstLen);
ssize_t utf8_length(const char *src);

45. Vector.h

legacy code.

* DO NOT USE: please use std::vector

46. VectorImpl.h

Ditto.

Guess you like

Origin blog.csdn.net/yinminsumeng/article/details/131175605