Android native开发:system/core/libutils

1. AndroidThreads.h

封装了thread相关函数,创建、设置优先级、设置名称等。提供c和c++的接口。

// 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

位操作辅助函数。

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

4. ByteOrder.h

参见:<android-base/endian.h>
system/core/base库介绍

5. CallStack.h

收集和打印一个thread的callstack。
参考:ProcessCallStack.h,收集一个process中所有thread callstack。

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

Mac os上没有off64_t,默认off_t是64位的。兼容性适配。

/* 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宏,遗留代码。
// 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

定义Android中的error code,和Linux或者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

对strcpm函数优化的模板函数。

// 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

内存映射文件的封装(mmap64、munmap),可以映射整个文件或者部分文件。

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

自定义Functor。

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

15. JenkinsHash.h

几个hash函数。

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
自定义双向链表。

19. Log.h

#include <log/log.h>

20. Looper.h

TODO

21. LruCache.h

一个实现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的注册监听和变更通知函数。

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

23. Mutex.h

一些thread相关attribute宏。
一个Win32平台上用的Mutex。

#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

<cutils/native_handle.h>中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

输出数据流的辅助类,可以输出到logcat、文件、string、为其他Printer添加前缀。

// 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

收集和打印一个process中所有thread的stack trace。
参考: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

对property文件的操作(解析、增改等),文件内容:
property1 = value1
property2 = value2

28. RefBase.h

 LightRefBase.h
 StrongPointer.h

几个相关的类放到一起。
1)文件内容组织:
(1)RefBase.h中包含class RefBase,class weakref_type(RefBase内部类),template class wp定义。
(2)weakref_type派生类weakref_impl定义在RefBase.cpp中,weakref_type只定义了一些接口,weakref_impl是实现类。
2)类功能和依赖关系:
(1)class RefBase,strong reference基类类,定义了incStrong,decStrong等接口,可用于template class sp。通过继承RefBase,为派生赋予strong ref相关功能。
(2)class weakref_type,weak reference基类,定义了incWeak,decWeak等接口,可用于template class wp。
(3)class weakref_impl,实现了一些调试相关功能,如果没有打开调试宏开关,功能和weakref_type一致。
(4)template class wp,weak pointer模板类,定义在RefBase.h中。
(5)template class sp,strong pointer模板类,定义在StrongPointer.h中。
wp和sp就是带引用计数(分别是强引用和弱引用)的智能指针。
(6)LightRefBase(派生模板类VirtualLightRefBase)是RefBase简化实现。
(7)RefBase和weakref_type都有成员方法可相互转换。
(8)在强引用和弱引用的基础上,可调用extendObjectLifetime()方法延长对象的声明周期。
在Binder实现中有很多应用。

// 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实现,RWLock/AutoRLock/AutoWLock,可能是遗留代码。

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

自定义的一个StopWatch,获取时间调用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

调用clock_gettime(CLOCK_BOOTTIME, &ts);获得系统启动的时长。

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

37. ThreadDefs.h

一些thread相关类型定义(如:thread_id_t,thread_func_t)和优先级enum定义。

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

获取系统时间,以及一些不同单位时间转换方法。

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

按行读取文本文件,并解析为单词(token)。

42. Trace.h

Trace辅助函数,在作用域内自动开始和停止,构造函数中调用atrace_begin,在析构函数中调用atrace_end。
<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

自定义的一些type traits,应该是早起对c++的补充。
辅助下面自定义的Vector实现。

44. Unicode.h

辅助函数,包括char16_t,char32_t比较、获取长度。
以及utf8、utf16、utf32的转换等函数。

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

遗留代码。

* DO NOT USE: please use std::vector

46. VectorImpl.h

同上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抓饼先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值