summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorVijay Venkatraman2017-01-05 12:39:38 -0600
committerVijay Venkatraman2017-01-24 16:51:36 -0600
commit75acc7bf81d43850694d39d2c45a20ca81d99379 (patch)
tree39f8b964c90102fbc6a8b954110342724cf6f394 /include
parent897bc9b2b38ead33aa883359593eb4356b68bda2 (diff)
downloadplatform-system-core-75acc7bf81d43850694d39d2c45a20ca81d99379.tar.gz
platform-system-core-75acc7bf81d43850694d39d2c45a20ca81d99379.tar.xz
platform-system-core-75acc7bf81d43850694d39d2c45a20ca81d99379.zip
Exporting C++ headers from system/core
Moved headers from include/libutils and include/libsysutils to libutils/include and libsysutils/include respectively, so they can be exported via these libs. They needed to be moved since Soong does not allow export from external folder. Added symlink from old locations. They are needed since Soong includes system/core/include by default. Once all modules are cleaned up to explicitly add the required libs, the symlinks will be removed. Moved headers of libutils to libutils_headers. They should be used by modules for header-only inlines. Added libutils_headers as dependency of libutils. Split of C++ headers into those that have no dependency and those that have dependency on libutils.so will be handled in a later CL. Test: Add above libs to shared lib of local module Change-Id: I122db72056b26b1f39bad1d9a0c2a1c5efda3550
Diffstat (limited to 'include')
l---------include/sysutils1
-rw-r--r--include/sysutils/FrameworkClient.h21
-rw-r--r--include/sysutils/FrameworkCommand.h38
-rw-r--r--include/sysutils/FrameworkListener.h51
-rw-r--r--include/sysutils/List.h334
-rw-r--r--include/sysutils/NetlinkEvent.h69
-rw-r--r--include/sysutils/NetlinkListener.h49
-rw-r--r--include/sysutils/ServiceManager.h30
-rw-r--r--include/sysutils/SocketClient.h88
-rw-r--r--include/sysutils/SocketClientCommand.h27
-rw-r--r--include/sysutils/SocketListener.h59
l---------include/utils1
-rw-r--r--include/utils/AndroidThreads.h125
-rw-r--r--include/utils/Atomic.h22
-rw-r--r--include/utils/BitSet.h294
-rw-r--r--include/utils/BlobCache.h249
-rw-r--r--include/utils/ByteOrder.h81
-rw-r--r--include/utils/CallStack.h72
-rw-r--r--include/utils/Compat.h83
-rw-r--r--include/utils/Condition.h165
-rw-r--r--include/utils/Debug.h48
-rw-r--r--include/utils/Endian.h35
-rw-r--r--include/utils/Errors.h88
-rw-r--r--include/utils/FastStrcmp.h54
-rw-r--r--include/utils/FileMap.h129
-rw-r--r--include/utils/Flattenable.h205
-rw-r--r--include/utils/Functor.h33
-rw-r--r--include/utils/JenkinsHash.h51
-rw-r--r--include/utils/KeyedVector.h216
-rw-r--r--include/utils/LinearTransform.h64
-rw-r--r--include/utils/List.h332
-rw-r--r--include/utils/Log.h72
-rw-r--r--include/utils/Looper.h487
-rw-r--r--include/utils/LruCache.h298
-rw-r--r--include/utils/Mutex.h167
-rw-r--r--include/utils/NativeHandle.h56
-rw-r--r--include/utils/Printer.h119
-rw-r--r--include/utils/ProcessCallStack.h79
-rw-r--r--include/utils/PropertyMap.h106
-rw-r--r--include/utils/RWLock.h126
-rw-r--r--include/utils/RefBase.h731
-rw-r--r--include/utils/Singleton.h85
-rw-r--r--include/utils/SortedVector.h277
-rw-r--r--include/utils/StopWatch.h64
-rw-r--r--include/utils/String16.h248
-rw-r--r--include/utils/String8.h404
-rw-r--r--include/utils/StrongPointer.h245
-rw-r--r--include/utils/SystemClock.h32
-rw-r--r--include/utils/Thread.h116
-rw-r--r--include/utils/ThreadDefs.h74
-rw-r--r--include/utils/Timers.h108
-rw-r--r--include/utils/Tokenizer.h136
-rw-r--r--include/utils/Trace.h69
-rw-r--r--include/utils/TypeHelpers.h336
-rw-r--r--include/utils/Unicode.h178
-rw-r--r--include/utils/Vector.h419
-rw-r--r--include/utils/VectorImpl.h183
-rw-r--r--include/utils/misc.h38
-rw-r--r--include/utils/threads.h38
59 files changed, 2 insertions, 8403 deletions
diff --git a/include/sysutils b/include/sysutils
new file mode 120000
index 000000000..1c8e85bd1
--- /dev/null
+++ b/include/sysutils
@@ -0,0 +1 @@
../libsysutils/include/sysutils/ \ No newline at end of file
diff --git a/include/sysutils/FrameworkClient.h b/include/sysutils/FrameworkClient.h
deleted file mode 100644
index 4a3f0de0e..000000000
--- a/include/sysutils/FrameworkClient.h
+++ /dev/null
@@ -1,21 +0,0 @@
1#ifndef _FRAMEWORK_CLIENT_H
2#define _FRAMEWORK_CLIENT_H
3
4#include "List.h"
5
6#include <pthread.h>
7
8class FrameworkClient {
9 int mSocket;
10 pthread_mutex_t mWriteMutex;
11
12public:
13 FrameworkClient(int sock);
14 virtual ~FrameworkClient() {}
15
16 int sendMsg(const char *msg);
17 int sendMsg(const char *msg, const char *data);
18};
19
20typedef android::sysutils::List<FrameworkClient *> FrameworkClientCollection;
21#endif
diff --git a/include/sysutils/FrameworkCommand.h b/include/sysutils/FrameworkCommand.h
deleted file mode 100644
index 3e6264bbd..000000000
--- a/include/sysutils/FrameworkCommand.h
+++ /dev/null
@@ -1,38 +0,0 @@
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef __FRAMEWORK_CMD_HANDLER_H
17#define __FRAMEWORK_CMD_HANDLER_H
18
19#include "List.h"
20
21class SocketClient;
22
23class FrameworkCommand {
24private:
25 const char *mCommand;
26
27public:
28
29 FrameworkCommand(const char *cmd);
30 virtual ~FrameworkCommand() { }
31
32 virtual int runCommand(SocketClient *c, int argc, char **argv) = 0;
33
34 const char *getCommand() { return mCommand; }
35};
36
37typedef android::sysutils::List<FrameworkCommand *> FrameworkCommandCollection;
38#endif
diff --git a/include/sysutils/FrameworkListener.h b/include/sysutils/FrameworkListener.h
deleted file mode 100644
index 2137069fb..000000000
--- a/include/sysutils/FrameworkListener.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef _FRAMEWORKSOCKETLISTENER_H
17#define _FRAMEWORKSOCKETLISTENER_H
18
19#include "SocketListener.h"
20#include "FrameworkCommand.h"
21
22class SocketClient;
23
24class FrameworkListener : public SocketListener {
25public:
26 static const int CMD_ARGS_MAX = 26;
27
28 /* 1 out of errorRate will be dropped */
29 int errorRate;
30
31private:
32 int mCommandCount;
33 bool mWithSeq;
34 FrameworkCommandCollection *mCommands;
35 bool mSkipToNextNullByte;
36
37public:
38 FrameworkListener(const char *socketName);
39 FrameworkListener(const char *socketName, bool withSeq);
40 FrameworkListener(int sock);
41 virtual ~FrameworkListener() {}
42
43protected:
44 void registerCmd(FrameworkCommand *cmd);
45 virtual bool onDataAvailable(SocketClient *c);
46
47private:
48 void dispatchCommand(SocketClient *c, char *data);
49 void init(const char *socketName, bool withSeq);
50};
51#endif
diff --git a/include/sysutils/List.h b/include/sysutils/List.h
deleted file mode 100644
index 31f7b37c1..000000000
--- a/include/sysutils/List.h
+++ /dev/null
@@ -1,334 +0,0 @@
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// Templated list class. Normally we'd use STL, but we don't have that.
19// This class mimics STL's interfaces.
20//
21// Objects are copied into the list with the '=' operator or with copy-
22// construction, so if the compiler's auto-generated versions won't work for
23// you, define your own.
24//
25// The only class you want to use from here is "List".
26//
27#ifndef _SYSUTILS_LIST_H
28#define _SYSUTILS_LIST_H
29
30#include <stddef.h>
31#include <stdint.h>
32
33namespace android {
34namespace sysutils {
35
36/*
37 * Doubly-linked list. Instantiate with "List<MyClass> myList".
38 *
39 * Objects added to the list are copied using the assignment operator,
40 * so this must be defined.
41 */
42template<typename T>
43class List
44{
45protected:
46 /*
47 * One element in the list.
48 */
49 class _Node {
50 public:
51 explicit _Node(const T& val) : mVal(val) {}
52 ~_Node() {}
53 inline T& getRef() { return mVal; }
54 inline const T& getRef() const { return mVal; }
55 inline _Node* getPrev() const { return mpPrev; }
56 inline _Node* getNext() const { return mpNext; }
57 inline void setVal(const T& val) { mVal = val; }
58 inline void setPrev(_Node* ptr) { mpPrev = ptr; }
59 inline void setNext(_Node* ptr) { mpNext = ptr; }
60 private:
61 friend class List;
62 friend class _ListIterator;
63 T mVal;
64 _Node* mpPrev;
65 _Node* mpNext;
66 };
67
68 /*
69 * Iterator for walking through the list.
70 */
71
72 template <typename TYPE>
73 struct CONST_ITERATOR {
74 typedef _Node const * NodePtr;
75 typedef const TYPE Type;
76 };
77
78 template <typename TYPE>
79 struct NON_CONST_ITERATOR {
80 typedef _Node* NodePtr;
81 typedef TYPE Type;
82 };
83
84 template<
85 typename U,
86 template <class> class Constness
87 >
88 class _ListIterator {
89 typedef _ListIterator<U, Constness> _Iter;
90 typedef typename Constness<U>::NodePtr _NodePtr;
91 typedef typename Constness<U>::Type _Type;
92
93 explicit _ListIterator(_NodePtr ptr) : mpNode(ptr) {}
94
95 public:
96 _ListIterator() {}
97 _ListIterator(const _Iter& rhs) : mpNode(rhs.mpNode) {}
98 ~_ListIterator() {}
99
100 // this will handle conversions from iterator to const_iterator
101 // (and also all convertible iterators)
102 // Here, in this implementation, the iterators can be converted
103 // if the nodes can be converted
104 template<typename V> explicit
105 _ListIterator(const V& rhs) : mpNode(rhs.mpNode) {}
106
107
108 /*
109 * Dereference operator. Used to get at the juicy insides.
110 */
111 _Type& operator*() const { return mpNode->getRef(); }
112 _Type* operator->() const { return &(mpNode->getRef()); }
113
114 /*
115 * Iterator comparison.
116 */
117 inline bool operator==(const _Iter& right) const {
118 return mpNode == right.mpNode; }
119
120 inline bool operator!=(const _Iter& right) const {
121 return mpNode != right.mpNode; }
122
123 /*
124 * handle comparisons between iterator and const_iterator
125 */
126 template<typename OTHER>
127 inline bool operator==(const OTHER& right) const {
128 return mpNode == right.mpNode; }
129
130 template<typename OTHER>
131 inline bool operator!=(const OTHER& right) const {
132 return mpNode != right.mpNode; }
133
134 /*
135 * Incr/decr, used to move through the list.
136 */
137 inline _Iter& operator++() { // pre-increment
138 mpNode = mpNode->getNext();
139 return *this;
140 }
141 const _Iter operator++(int) { // post-increment
142 _Iter tmp(*this);
143 mpNode = mpNode->getNext();
144 return tmp;
145 }
146 inline _Iter& operator--() { // pre-increment
147 mpNode = mpNode->getPrev();
148 return *this;
149 }
150 const _Iter operator--(int) { // post-increment
151 _Iter tmp(*this);
152 mpNode = mpNode->getPrev();
153 return tmp;
154 }
155
156 inline _NodePtr getNode() const { return mpNode; }
157
158 _NodePtr mpNode; /* should be private, but older gcc fails */
159 private:
160 friend class List;
161 };
162
163public:
164 List() {
165 prep();
166 }
167 List(const List<T>& src) { // copy-constructor
168 prep();
169 insert(begin(), src.begin(), src.end());
170 }
171 virtual ~List() {
172 clear();
173 delete[] (unsigned char*) mpMiddle;
174 }
175
176 typedef _ListIterator<T, NON_CONST_ITERATOR> iterator;
177 typedef _ListIterator<T, CONST_ITERATOR> const_iterator;
178
179 List<T>& operator=(const List<T>& right);
180
181 /* returns true if the list is empty */
182 inline bool empty() const { return mpMiddle->getNext() == mpMiddle; }
183
184 /* return #of elements in list */
185 size_t size() const {
186 return size_t(distance(begin(), end()));
187 }
188
189 /*
190 * Return the first element or one past the last element. The
191 * _Node* we're returning is converted to an "iterator" by a
192 * constructor in _ListIterator.
193 */
194 inline iterator begin() {
195 return iterator(mpMiddle->getNext());
196 }
197 inline const_iterator begin() const {
198 return const_iterator(const_cast<_Node const*>(mpMiddle->getNext()));
199 }
200 inline iterator end() {
201 return iterator(mpMiddle);
202 }
203 inline const_iterator end() const {
204 return const_iterator(const_cast<_Node const*>(mpMiddle));
205 }
206
207 /* add the object to the head or tail of the list */
208 void push_front(const T& val) { insert(begin(), val); }
209 void push_back(const T& val) { insert(end(), val); }
210
211 /* insert before the current node; returns iterator at new node */
212 iterator insert(iterator posn, const T& val)
213 {
214 _Node* newNode = new _Node(val); // alloc & copy-construct
215 newNode->setNext(posn.getNode());
216 newNode->setPrev(posn.getNode()->getPrev());
217 posn.getNode()->getPrev()->setNext(newNode);
218 posn.getNode()->setPrev(newNode);
219 return iterator(newNode);
220 }
221
222 /* insert a range of elements before the current node */
223 void insert(iterator posn, const_iterator first, const_iterator last) {
224 for ( ; first != last; ++first)
225 insert(posn, *first);
226 }
227
228 /* remove one entry; returns iterator at next node */
229 iterator erase(iterator posn) {
230 _Node* pNext = posn.getNode()->getNext();
231 _Node* pPrev = posn.getNode()->getPrev();
232 pPrev->setNext(pNext);
233 pNext->setPrev(pPrev);
234 delete posn.getNode();
235 return iterator(pNext);
236 }
237
238 /* remove a range of elements */
239 iterator erase(iterator first, iterator last) {
240 while (first != last)
241 erase(first++); // don't erase than incr later!
242 return iterator(last);
243 }
244
245 /* remove all contents of the list */
246 void clear() {
247 _Node* pCurrent = mpMiddle->getNext();
248 _Node* pNext;
249
250 while (pCurrent != mpMiddle) {
251 pNext = pCurrent->getNext();
252 delete pCurrent;
253 pCurrent = pNext;
254 }
255 mpMiddle->setPrev(mpMiddle);
256 mpMiddle->setNext(mpMiddle);
257 }
258
259 /*
260 * Measure the distance between two iterators. On exist, "first"
261 * will be equal to "last". The iterators must refer to the same
262 * list.
263 *
264 * FIXME: This is actually a generic iterator function. It should be a
265 * template function at the top-level with specializations for things like
266 * vector<>, which can just do pointer math). Here we limit it to
267 * _ListIterator of the same type but different constness.
268 */
269 template<
270 typename U,
271 template <class> class CL,
272 template <class> class CR
273 >
274 ptrdiff_t distance(
275 _ListIterator<U, CL> first, _ListIterator<U, CR> last) const
276 {
277 ptrdiff_t count = 0;
278 while (first != last) {
279 ++first;
280 ++count;
281 }
282 return count;
283 }
284
285private:
286 /*
287 * I want a _Node but don't need it to hold valid data. More
288 * to the point, I don't want T's constructor to fire, since it
289 * might have side-effects or require arguments. So, we do this
290 * slightly uncouth storage alloc.
291 */
292 void prep() {
293 mpMiddle = (_Node*) new unsigned char[sizeof(_Node)];
294 mpMiddle->setPrev(mpMiddle);
295 mpMiddle->setNext(mpMiddle);
296 }
297
298 /*
299 * This node plays the role of "pointer to head" and "pointer to tail".
300 * It sits in the middle of a circular list of nodes. The iterator
301 * runs around the circle until it encounters this one.
302 */
303 _Node* mpMiddle;
304};
305
306/*
307 * Assignment operator.
308 *
309 * The simplest way to do this would be to clear out the target list and
310 * fill it with the source. However, we can speed things along by
311 * re-using existing elements.
312 */
313template<class T>
314List<T>& List<T>::operator=(const List<T>& right)
315{
316 if (this == &right)
317 return *this; // self-assignment
318 iterator firstDst = begin();
319 iterator lastDst = end();
320 const_iterator firstSrc = right.begin();
321 const_iterator lastSrc = right.end();
322 while (firstSrc != lastSrc && firstDst != lastDst)
323 *firstDst++ = *firstSrc++;
324 if (firstSrc == lastSrc) // ran out of elements in source?
325 erase(firstDst, lastDst); // yes, erase any extras
326 else
327 insert(lastDst, firstSrc, lastSrc); // copy remaining over
328 return *this;
329}
330
331}; // namespace sysutils
332}; // namespace android
333
334#endif // _SYSUTILS_LIST_H
diff --git a/include/sysutils/NetlinkEvent.h b/include/sysutils/NetlinkEvent.h
deleted file mode 100644
index b80f3ea44..000000000
--- a/include/sysutils/NetlinkEvent.h
+++ /dev/null
@@ -1,69 +0,0 @@
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef _NETLINKEVENT_H
17#define _NETLINKEVENT_H
18
19#include <sysutils/NetlinkListener.h>
20
21#define NL_PARAMS_MAX 32
22
23class NetlinkEvent {
24public:
25 enum class Action {
26 kUnknown = 0,
27 kAdd = 1,
28 kRemove = 2,
29 kChange = 3,
30 kLinkUp = 4,
31 kLinkDown = 5,
32 kAddressUpdated = 6,
33 kAddressRemoved = 7,
34 kRdnss = 8,
35 kRouteUpdated = 9,
36 kRouteRemoved = 10,
37 };
38
39private:
40 int mSeq;
41 char *mPath;
42 Action mAction;
43 char *mSubsystem;
44 char *mParams[NL_PARAMS_MAX];
45
46public:
47 NetlinkEvent();
48 virtual ~NetlinkEvent();
49
50 bool decode(char *buffer, int size, int format = NetlinkListener::NETLINK_FORMAT_ASCII);
51 const char *findParam(const char *paramName);
52
53 const char *getSubsystem() { return mSubsystem; }
54 Action getAction() { return mAction; }
55
56 void dump();
57
58 protected:
59 bool parseBinaryNetlinkMessage(char *buffer, int size);
60 bool parseAsciiNetlinkMessage(char *buffer, int size);
61 bool parseIfInfoMessage(const struct nlmsghdr *nh);
62 bool parseIfAddrMessage(const struct nlmsghdr *nh);
63 bool parseUlogPacketMessage(const struct nlmsghdr *nh);
64 bool parseNfPacketMessage(struct nlmsghdr *nh);
65 bool parseRtMessage(const struct nlmsghdr *nh);
66 bool parseNdUserOptMessage(const struct nlmsghdr *nh);
67};
68
69#endif
diff --git a/include/sysutils/NetlinkListener.h b/include/sysutils/NetlinkListener.h
deleted file mode 100644
index 82465d697..000000000
--- a/include/sysutils/NetlinkListener.h
+++ /dev/null
@@ -1,49 +0,0 @@
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef _NETLINKLISTENER_H
17#define _NETLINKLISTENER_H
18
19#include "SocketListener.h"
20
21class NetlinkEvent;
22
23class NetlinkListener : public SocketListener {
24 char mBuffer[64 * 1024] __attribute__((aligned(4)));
25 int mFormat;
26
27public:
28 static const int NETLINK_FORMAT_ASCII = 0;
29 static const int NETLINK_FORMAT_BINARY = 1;
30 static const int NETLINK_FORMAT_BINARY_UNICAST = 2;
31
32#if 1
33 /* temporary version until we can get Motorola to update their
34 * ril.so. Their prebuilt ril.so is using this private class
35 * so changing the NetlinkListener() constructor breaks their ril.
36 */
37 NetlinkListener(int socket);
38 NetlinkListener(int socket, int format);
39#else
40 NetlinkListener(int socket, int format = NETLINK_FORMAT_ASCII);
41#endif
42 virtual ~NetlinkListener() {}
43
44protected:
45 virtual bool onDataAvailable(SocketClient *cli);
46 virtual void onEvent(NetlinkEvent *evt) = 0;
47};
48
49#endif
diff --git a/include/sysutils/ServiceManager.h b/include/sysutils/ServiceManager.h
deleted file mode 100644
index c31dd8f22..000000000
--- a/include/sysutils/ServiceManager.h
+++ /dev/null
@@ -1,30 +0,0 @@
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _SERVICE_MANAGER_H
18#define _SERVICE_MANAGER_H
19
20class ServiceManager {
21public:
22 ServiceManager();
23 virtual ~ServiceManager() {}
24
25 int start(const char *name);
26 int stop(const char *name);
27 bool isRunning(const char *name);
28};
29
30#endif
diff --git a/include/sysutils/SocketClient.h b/include/sysutils/SocketClient.h
deleted file mode 100644
index 1004f0611..000000000
--- a/include/sysutils/SocketClient.h
+++ /dev/null
@@ -1,88 +0,0 @@
1#ifndef _SOCKET_CLIENT_H
2#define _SOCKET_CLIENT_H
3
4#include "List.h"
5
6#include <pthread.h>
7#include <cutils/atomic.h>
8#include <sys/types.h>
9#include <sys/uio.h>
10
11class SocketClient {
12 int mSocket;
13 bool mSocketOwned;
14 pthread_mutex_t mWriteMutex;
15
16 // Peer process ID
17 pid_t mPid;
18
19 // Peer user ID
20 uid_t mUid;
21
22 // Peer group ID
23 gid_t mGid;
24
25 // Reference count (starts at 1)
26 pthread_mutex_t mRefCountMutex;
27 int mRefCount;
28
29 int mCmdNum;
30
31 bool mUseCmdNum;
32
33public:
34 SocketClient(int sock, bool owned);
35 SocketClient(int sock, bool owned, bool useCmdNum);
36 virtual ~SocketClient();
37
38 int getSocket() { return mSocket; }
39 pid_t getPid() const { return mPid; }
40 uid_t getUid() const { return mUid; }
41 gid_t getGid() const { return mGid; }
42 void setCmdNum(int cmdNum) {
43 android_atomic_release_store(cmdNum, &mCmdNum);
44 }
45 int getCmdNum() { return mCmdNum; }
46
47 // Send null-terminated C strings:
48 int sendMsg(int code, const char *msg, bool addErrno);
49 int sendMsg(int code, const char *msg, bool addErrno, bool useCmdNum);
50 int sendMsg(const char *msg);
51
52 // Provides a mechanism to send a response code to the client.
53 // Sends the code and a null character.
54 int sendCode(int code);
55
56 // Provides a mechanism to send binary data to client.
57 // Sends the code and a null character, followed by 4 bytes of
58 // big-endian length, and the data.
59 int sendBinaryMsg(int code, const void *data, int len);
60
61 // Sending binary data:
62 int sendData(const void *data, int len);
63 // iovec contents not preserved through call
64 int sendDatav(struct iovec *iov, int iovcnt);
65
66 // Optional reference counting. Reference count starts at 1. If
67 // it's decremented to 0, it deletes itself.
68 // SocketListener creates a SocketClient (at refcount 1) and calls
69 // decRef() when it's done with the client.
70 void incRef();
71 bool decRef(); // returns true at 0 (but note: SocketClient already deleted)
72
73 // return a new string in quotes with '\\' and '\"' escaped for "my arg"
74 // transmissions
75 static char *quoteArg(const char *arg);
76
77private:
78 void init(int socket, bool owned, bool useCmdNum);
79
80 // Sending binary data. The caller should make sure this is protected
81 // from multiple threads entering simultaneously.
82 // returns 0 if successful, -1 if there is a 0 byte write or if any
83 // other error occurred (use errno to get the error)
84 int sendDataLockedv(struct iovec *iov, int iovcnt);
85};
86
87typedef android::sysutils::List<SocketClient *> SocketClientCollection;
88#endif
diff --git a/include/sysutils/SocketClientCommand.h b/include/sysutils/SocketClientCommand.h
deleted file mode 100644
index 746bc2587..000000000
--- a/include/sysutils/SocketClientCommand.h
+++ /dev/null
@@ -1,27 +0,0 @@
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef _SOCKETCLIENTCOMMAND_H
17#define _SOCKETCLIENTCOMMAND_H
18
19#include <sysutils/SocketClient.h>
20
21class SocketClientCommand {
22public:
23 virtual ~SocketClientCommand() { }
24 virtual void runSocketCommand(SocketClient *client) = 0;
25};
26
27#endif
diff --git a/include/sysutils/SocketListener.h b/include/sysutils/SocketListener.h
deleted file mode 100644
index bc93b8635..000000000
--- a/include/sysutils/SocketListener.h
+++ /dev/null
@@ -1,59 +0,0 @@
1/*
2 * Copyright (C) 2008-2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef _SOCKETLISTENER_H
17#define _SOCKETLISTENER_H
18
19#include <pthread.h>
20
21#include <sysutils/SocketClient.h>
22#include "SocketClientCommand.h"
23
24class SocketListener {
25 bool mListen;
26 const char *mSocketName;
27 int mSock;
28 SocketClientCollection *mClients;
29 pthread_mutex_t mClientsLock;
30 int mCtrlPipe[2];
31 pthread_t mThread;
32 bool mUseCmdNum;
33
34public:
35 SocketListener(const char *socketName, bool listen);
36 SocketListener(const char *socketName, bool listen, bool useCmdNum);
37 SocketListener(int socketFd, bool listen);
38
39 virtual ~SocketListener();
40 int startListener();
41 int startListener(int backlog);
42 int stopListener();
43
44 void sendBroadcast(int code, const char *msg, bool addErrno);
45
46 void runOnEachSocket(SocketClientCommand *command);
47
48 bool release(SocketClient *c) { return release(c, true); }
49
50protected:
51 virtual bool onDataAvailable(SocketClient *c) = 0;
52
53private:
54 bool release(SocketClient *c, bool wakeup);
55 static void *threadStart(void *obj);
56 void runListener();
57 void init(const char *socketName, int socketFd, bool listen, bool useCmdNum);
58};
59#endif
diff --git a/include/utils b/include/utils
new file mode 120000
index 000000000..e8476fd19
--- /dev/null
+++ b/include/utils
@@ -0,0 +1 @@
../libutils/include/utils/ \ No newline at end of file
diff --git a/include/utils/AndroidThreads.h b/include/utils/AndroidThreads.h
deleted file mode 100644
index 4c2dd49f6..000000000
--- a/include/utils/AndroidThreads.h
+++ /dev/null
@@ -1,125 +0,0 @@
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _LIBS_UTILS_ANDROID_THREADS_H
18#define _LIBS_UTILS_ANDROID_THREADS_H
19
20#include <stdint.h>
21#include <sys/types.h>
22
23#if !defined(_WIN32)
24# include <pthread.h>
25#endif
26
27#include <utils/ThreadDefs.h>
28
29// ---------------------------------------------------------------------------
30// C API
31
32#ifdef __cplusplus
33extern "C" {
34#endif
35
36// Create and run a new thread.
37extern int androidCreateThread(android_thread_func_t, void *);
38
39// Create thread with lots of parameters
40extern int androidCreateThreadEtc(android_thread_func_t entryFunction,
41 void *userData,
42 const char* threadName,
43 int32_t threadPriority,
44 size_t threadStackSize,
45 android_thread_id_t *threadId);
46
47// Get some sort of unique identifier for the current thread.
48extern android_thread_id_t androidGetThreadId();
49
50// Low-level thread creation -- never creates threads that can
51// interact with the Java VM.
52extern int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
53 void *userData,
54 const char* threadName,
55 int32_t threadPriority,
56 size_t threadStackSize,
57 android_thread_id_t *threadId);
58
59// set the same of the running thread
60extern void androidSetThreadName(const char* name);
61
62// Used by the Java Runtime to control how threads are created, so that
63// they can be proper and lovely Java threads.
64typedef int (*android_create_thread_fn)(android_thread_func_t entryFunction,
65 void *userData,
66 const char* threadName,
67 int32_t threadPriority,
68 size_t threadStackSize,
69 android_thread_id_t *threadId);
70
71extern void androidSetCreateThreadFunc(android_create_thread_fn func);
72
73// ------------------------------------------------------------------
74// Extra functions working with raw pids.
75
76#if defined(__ANDROID__)
77// Change the priority AND scheduling group of a particular thread. The priority
78// should be one of the ANDROID_PRIORITY constants. Returns INVALID_OPERATION
79// if the priority set failed, else another value if just the group set failed;
80// in either case errno is set. Thread ID zero means current thread.
81extern int androidSetThreadPriority(pid_t tid, int prio);
82
83// Get the current priority of a particular thread. Returns one of the
84// ANDROID_PRIORITY constants or a negative result in case of error.
85extern int androidGetThreadPriority(pid_t tid);
86#endif
87
88#ifdef __cplusplus
89} // extern "C"
90#endif
91
92// ----------------------------------------------------------------------------
93// C++ API
94#ifdef __cplusplus
95namespace android {
96// ----------------------------------------------------------------------------
97
98// Create and run a new thread.
99inline bool createThread(thread_func_t f, void *a) {
100 return androidCreateThread(f, a) ? true : false;
101}
102
103// Create thread with lots of parameters
104inline bool createThreadEtc(thread_func_t entryFunction,
105 void *userData,
106 const char* threadName = "android:unnamed_thread",
107 int32_t threadPriority = PRIORITY_DEFAULT,
108 size_t threadStackSize = 0,
109 thread_id_t *threadId = 0)
110{
111 return androidCreateThreadEtc(entryFunction, userData, threadName,
112 threadPriority, threadStackSize, threadId) ? true : false;
113}
114
115// Get some sort of unique identifier for the current thread.
116inline thread_id_t getThreadId() {
117 return androidGetThreadId();
118}
119
120// ----------------------------------------------------------------------------
121}; // namespace android
122#endif // __cplusplus
123// ----------------------------------------------------------------------------
124
125#endif // _LIBS_UTILS_ANDROID_THREADS_H
diff --git a/include/utils/Atomic.h b/include/utils/Atomic.h
deleted file mode 100644
index 7eb476c94..000000000
--- a/include/utils/Atomic.h
+++ /dev/null
@@ -1,22 +0,0 @@
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_UTILS_ATOMIC_H
18#define ANDROID_UTILS_ATOMIC_H
19
20#include <cutils/atomic.h>
21
22#endif // ANDROID_UTILS_ATOMIC_H
diff --git a/include/utils/BitSet.h b/include/utils/BitSet.h
deleted file mode 100644
index 8c612931d..000000000
--- a/include/utils/BitSet.h
+++ /dev/null
@@ -1,294 +0,0 @@
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef UTILS_BITSET_H
18#define UTILS_BITSET_H
19
20#include <stdint.h>
21#include <utils/TypeHelpers.h>
22
23/*
24 * Contains some bit manipulation helpers.
25 */
26
27namespace android {
28
29// A simple set of 32 bits that can be individually marked or cleared.
30struct BitSet32 {
31 uint32_t value;
32
33 inline BitSet32() : value(0UL) { }
34 explicit inline BitSet32(uint32_t value) : value(value) { }
35
36 // Gets the value associated with a particular bit index.
37 static inline uint32_t valueForBit(uint32_t n) { return 0x80000000UL >> n; }
38
39 // Clears the bit set.
40 inline void clear() { clear(value); }
41
42 static inline void clear(uint32_t& value) { value = 0UL; }
43
44 // Returns the number of marked bits in the set.
45 inline uint32_t count() const { return count(value); }
46
47 static inline uint32_t count(uint32_t value) { return __builtin_popcountl(value); }
48
49 // Returns true if the bit set does not contain any marked bits.
50 inline bool isEmpty() const { return isEmpty(value); }
51
52 static inline bool isEmpty(uint32_t value) { return ! value; }
53
54 // Returns true if the bit set does not contain any unmarked bits.
55 inline bool isFull() const { return isFull(value); }
56
57 static inline bool isFull(uint32_t value) { return value == 0xffffffffUL; }
58
59 // Returns true if the specified bit is marked.
60 inline bool hasBit(uint32_t n) const { return hasBit(value, n); }
61
62 static inline bool hasBit(uint32_t value, uint32_t n) { return value & valueForBit(n); }
63
64 // Marks the specified bit.
65 inline void markBit(uint32_t n) { markBit(value, n); }
66
67 static inline void markBit (uint32_t& value, uint32_t n) { value |= valueForBit(n); }
68
69 // Clears the specified bit.
70 inline void clearBit(uint32_t n) { clearBit(value, n); }
71
72 static inline void clearBit(uint32_t& value, uint32_t n) { value &= ~ valueForBit(n); }
73
74 // Finds the first marked bit in the set.
75 // Result is undefined if all bits are unmarked.
76 inline uint32_t firstMarkedBit() const { return firstMarkedBit(value); }
77
78 static uint32_t firstMarkedBit(uint32_t value) { return clz_checked(value); }
79
80 // Finds the first unmarked bit in the set.
81 // Result is undefined if all bits are marked.
82 inline uint32_t firstUnmarkedBit() const { return firstUnmarkedBit(value); }
83
84 static inline uint32_t firstUnmarkedBit(uint32_t value) { return clz_checked(~ value); }
85
86 // Finds the last marked bit in the set.
87 // Result is undefined if all bits are unmarked.
88 inline uint32_t lastMarkedBit() const { return lastMarkedBit(value); }
89
90 static inline uint32_t lastMarkedBit(uint32_t value) { return 31 - ctz_checked(value); }
91
92 // Finds the first marked bit in the set and clears it. Returns the bit index.
93 // Result is undefined if all bits are unmarked.
94 inline uint32_t clearFirstMarkedBit() { return clearFirstMarkedBit(value); }
95
96 static inline uint32_t clearFirstMarkedBit(uint32_t& value) {
97 uint32_t n = firstMarkedBit(value);
98 clearBit(value, n);
99 return n;
100 }
101
102 // Finds the first unmarked bit in the set and marks it. Returns the bit index.
103 // Result is undefined if all bits are marked.
104 inline uint32_t markFirstUnmarkedBit() { return markFirstUnmarkedBit(value); }
105
106 static inline uint32_t markFirstUnmarkedBit(uint32_t& value) {
107 uint32_t n = firstUnmarkedBit(value);
108 markBit(value, n);
109 return n;
110 }
111
112 // Finds the last marked bit in the set and clears it. Returns the bit index.
113 // Result is undefined if all bits are unmarked.
114 inline uint32_t clearLastMarkedBit() { return clearLastMarkedBit(value); }
115
116 static inline uint32_t clearLastMarkedBit(uint32_t& value) {
117 uint32_t n = lastMarkedBit(value);
118 clearBit(value, n);
119 return n;
120 }
121
122 // Gets the index of the specified bit in the set, which is the number of
123 // marked bits that appear before the specified bit.
124 inline uint32_t getIndexOfBit(uint32_t n) const {
125 return getIndexOfBit(value, n);
126 }
127
128 static inline uint32_t getIndexOfBit(uint32_t value, uint32_t n) {
129 return __builtin_popcountl(value & ~(0xffffffffUL >> n));
130 }
131
132 inline bool operator== (const BitSet32& other) const { return value == other.value; }
133 inline bool operator!= (const BitSet32& other) const { return value != other.value; }
134 inline BitSet32 operator& (const BitSet32& other) const {
135 return BitSet32(value & other.value);
136 }
137 inline BitSet32& operator&= (const BitSet32& other) {
138 value &= other.value;
139 return *this;
140 }
141 inline BitSet32 operator| (const BitSet32& other) const {
142 return BitSet32(value | other.value);
143 }
144 inline BitSet32& operator|= (const BitSet32& other) {
145 value |= other.value;
146 return *this;
147 }
148
149private:
150 // We use these helpers as the signature of __builtin_c{l,t}z has "unsigned int" for the
151 // input, which is only guaranteed to be 16b, not 32. The compiler should optimize this away.
152 static inline uint32_t clz_checked(uint32_t value) {
153 if (sizeof(unsigned int) == sizeof(uint32_t)) {
154 return __builtin_clz(value);
155 } else {
156 return __builtin_clzl(value);
157 }
158 }
159
160 static inline uint32_t ctz_checked(uint32_t value) {
161 if (sizeof(unsigned int) == sizeof(uint32_t)) {
162 return __builtin_ctz(value);
163 } else {
164 return __builtin_ctzl(value);
165 }
166 }
167};
168
169ANDROID_BASIC_TYPES_TRAITS(BitSet32)
170
171// A simple set of 64 bits that can be individually marked or cleared.
172struct BitSet64 {
173 uint64_t value;
174
175 inline BitSet64() : value(0ULL) { }
176 explicit inline BitSet64(uint64_t value) : value(value) { }
177
178 // Gets the value associated with a particular bit index.
179 static inline uint64_t valueForBit(uint32_t n) { return 0x8000000000000000ULL >> n; }
180
181 // Clears the bit set.
182 inline void clear() { clear(value); }
183
184 static inline void clear(uint64_t& value) { value = 0ULL; }
185
186 // Returns the number of marked bits in the set.
187 inline uint32_t count() const { return count(value); }
188
189 static inline uint32_t count(uint64_t value) { return __builtin_popcountll(value); }
190
191 // Returns true if the bit set does not contain any marked bits.
192 inline bool isEmpty() const { return isEmpty(value); }
193
194 static inline bool isEmpty(uint64_t value) { return ! value; }
195
196 // Returns true if the bit set does not contain any unmarked bits.
197 inline bool isFull() const { return isFull(value); }
198
199 static inline bool isFull(uint64_t value) { return value == 0xffffffffffffffffULL; }
200
201 // Returns true if the specified bit is marked.
202 inline bool hasBit(uint32_t n) const { return hasBit(value, n); }
203
204 static inline bool hasBit(uint64_t value, uint32_t n) { return value & valueForBit(n); }
205
206 // Marks the specified bit.
207 inline void markBit(uint32_t n) { markBit(value, n); }
208
209 static inline void markBit(uint64_t& value, uint32_t n) { value |= valueForBit(n); }
210
211 // Clears the specified bit.
212 inline void clearBit(uint32_t n) { clearBit(value, n); }
213
214 static inline void clearBit(uint64_t& value, uint32_t n) { value &= ~ valueForBit(n); }
215
216 // Finds the first marked bit in the set.
217 // Result is undefined if all bits are unmarked.
218 inline uint32_t firstMarkedBit() const { return firstMarkedBit(value); }
219
220 static inline uint32_t firstMarkedBit(uint64_t value) { return __builtin_clzll(value); }
221
222 // Finds the first unmarked bit in the set.
223 // Result is undefined if all bits are marked.
224 inline uint32_t firstUnmarkedBit() const { return firstUnmarkedBit(value); }
225
226 static inline uint32_t firstUnmarkedBit(uint64_t value) { return __builtin_clzll(~ value); }
227
228 // Finds the last marked bit in the set.
229 // Result is undefined if all bits are unmarked.
230 inline uint32_t lastMarkedBit() const { return lastMarkedBit(value); }
231
232 static inline uint32_t lastMarkedBit(uint64_t value) { return 63 - __builtin_ctzll(value); }
233
234 // Finds the first marked bit in the set and clears it. Returns the bit index.
235 // Result is undefined if all bits are unmarked.
236 inline uint32_t clearFirstMarkedBit() { return clearFirstMarkedBit(value); }
237
238 static inline uint32_t clearFirstMarkedBit(uint64_t& value) {
239 uint64_t n = firstMarkedBit(value);
240 clearBit(value, n);
241 return n;
242 }
243
244 // Finds the first unmarked bit in the set and marks it. Returns the bit index.
245 // Result is undefined if all bits are marked.
246 inline uint32_t markFirstUnmarkedBit() { return markFirstUnmarkedBit(value); }
247
248 static inline uint32_t markFirstUnmarkedBit(uint64_t& value) {
249 uint64_t n = firstUnmarkedBit(value);
250 markBit(value, n);
251 return n;
252 }
253
254 // Finds the last marked bit in the set and clears it. Returns the bit index.
255 // Result is undefined if all bits are unmarked.
256 inline uint32_t clearLastMarkedBit() { return clearLastMarkedBit(value); }
257
258 static inline uint32_t clearLastMarkedBit(uint64_t& value) {
259 uint64_t n = lastMarkedBit(value);
260 clearBit(value, n);
261 return n;
262 }
263
264 // Gets the index of the specified bit in the set, which is the number of
265 // marked bits that appear before the specified bit.
266 inline uint32_t getIndexOfBit(uint32_t n) const { return getIndexOfBit(value, n); }
267
268 static inline uint32_t getIndexOfBit(uint64_t value, uint32_t n) {
269 return __builtin_popcountll(value & ~(0xffffffffffffffffULL >> n));
270 }
271
272 inline bool operator== (const BitSet64& other) const { return value == other.value; }
273 inline bool operator!= (const BitSet64& other) const { return value != other.value; }
274 inline BitSet64 operator& (const BitSet64& other) const {
275 return BitSet64(value & other.value);
276 }
277 inline BitSet64& operator&= (const BitSet64& other) {
278 value &= other.value;
279 return *this;
280 }
281 inline BitSet64 operator| (const BitSet64& other) const {
282 return BitSet64(value | other.value);
283 }
284 inline BitSet64& operator|= (const BitSet64& other) {
285 value |= other.value;
286 return *this;
287 }
288};
289
290ANDROID_BASIC_TYPES_TRAITS(BitSet64)
291
292} // namespace android
293
294#endif // UTILS_BITSET_H
diff --git a/include/utils/BlobCache.h b/include/utils/BlobCache.h
deleted file mode 100644
index 65dca9fb4..000000000
--- a/include/utils/BlobCache.h
+++ /dev/null
@@ -1,249 +0,0 @@
1/*
2 ** Copyright 2011, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 ** http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
17#ifndef ANDROID_BLOB_CACHE_H
18#define ANDROID_BLOB_CACHE_H
19
20#include <stddef.h>
21
22#include <utils/Flattenable.h>
23#include <utils/RefBase.h>
24#include <utils/SortedVector.h>
25#include <utils/threads.h>
26
27namespace android {
28
29// A BlobCache is an in-memory cache for binary key/value pairs. A BlobCache
30// does NOT provide any thread-safety guarantees.
31//
32// The cache contents can be serialized to an in-memory buffer or mmap'd file
33// and then reloaded in a subsequent execution of the program. This
34// serialization is non-portable and the data should only be used by the device
35// that generated it.
36class BlobCache : public RefBase {
37
38public:
39
40 // Create an empty blob cache. The blob cache will cache key/value pairs
41 // with key and value sizes less than or equal to maxKeySize and
42 // maxValueSize, respectively. The total combined size of ALL cache entries
43 // (key sizes plus value sizes) will not exceed maxTotalSize.
44 BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize);
45
46 // set inserts a new binary value into the cache and associates it with the
47 // given binary key. If the key or value are too large for the cache then
48 // the cache remains unchanged. This includes the case where a different
49 // value was previously associated with the given key - the old value will
50 // remain in the cache. If the given key and value are small enough to be
51 // put in the cache (based on the maxKeySize, maxValueSize, and maxTotalSize
52 // values specified to the BlobCache constructor), then the key/value pair
53 // will be in the cache after set returns. Note, however, that a subsequent
54 // call to set may evict old key/value pairs from the cache.
55 //
56 // Preconditions:
57 // key != NULL
58 // 0 < keySize
59 // value != NULL
60 // 0 < valueSize
61 void set(const void* key, size_t keySize, const void* value,
62 size_t valueSize);
63
64 // get retrieves from the cache the binary value associated with a given
65 // binary key. If the key is present in the cache then the length of the
66 // binary value associated with that key is returned. If the value argument
67 // is non-NULL and the size of the cached value is less than valueSize bytes
68 // then the cached value is copied into the buffer pointed to by the value
69 // argument. If the key is not present in the cache then 0 is returned and
70 // the buffer pointed to by the value argument is not modified.
71 //
72 // Note that when calling get multiple times with the same key, the later
73 // calls may fail, returning 0, even if earlier calls succeeded. The return
74 // value must be checked for each call.
75 //
76 // Preconditions:
77 // key != NULL
78 // 0 < keySize
79 // 0 <= valueSize
80 size_t get(const void* key, size_t keySize, void* value, size_t valueSize);
81
82
83 // getFlattenedSize returns the number of bytes needed to store the entire
84 // serialized cache.
85 size_t getFlattenedSize() const;
86
87 // flatten serializes the current contents of the cache into the memory
88 // pointed to by 'buffer'. The serialized cache contents can later be
89 // loaded into a BlobCache object using the unflatten method. The contents
90 // of the BlobCache object will not be modified.
91 //
92 // Preconditions:
93 // size >= this.getFlattenedSize()
94 status_t flatten(void* buffer, size_t size) const;
95
96 // unflatten replaces the contents of the cache with the serialized cache
97 // contents in the memory pointed to by 'buffer'. The previous contents of
98 // the BlobCache will be evicted from the cache. If an error occurs while
99 // unflattening the serialized cache contents then the BlobCache will be
100 // left in an empty state.
101 //
102 status_t unflatten(void const* buffer, size_t size);
103
104private:
105 // Copying is disallowed.
106 BlobCache(const BlobCache&);
107 void operator=(const BlobCache&);
108
109 // A random function helper to get around MinGW not having nrand48()
110 long int blob_random();
111
112 // clean evicts a randomly chosen set of entries from the cache such that
113 // the total size of all remaining entries is less than mMaxTotalSize/2.
114 void clean();
115
116 // isCleanable returns true if the cache is full enough for the clean method
117 // to have some effect, and false otherwise.
118 bool isCleanable() const;
119
120 // A Blob is an immutable sized unstructured data blob.
121 class Blob : public RefBase {
122 public:
123 Blob(const void* data, size_t size, bool copyData);
124 ~Blob();
125
126 bool operator<(const Blob& rhs) const;
127
128 const void* getData() const;
129 size_t getSize() const;
130
131 private:
132 // Copying is not allowed.
133 Blob(const Blob&);
134 void operator=(const Blob&);
135
136 // mData points to the buffer containing the blob data.
137 const void* mData;
138
139 // mSize is the size of the blob data in bytes.
140 size_t mSize;
141
142 // mOwnsData indicates whether or not this Blob object should free the
143 // memory pointed to by mData when the Blob gets destructed.
144 bool mOwnsData;
145 };
146
147 // A CacheEntry is a single key/value pair in the cache.
148 class CacheEntry {
149 public:
150 CacheEntry();
151 CacheEntry(const sp<Blob>& key, const sp<Blob>& value);
152 CacheEntry(const CacheEntry& ce);
153
154 bool operator<(const CacheEntry& rhs) const;
155 const CacheEntry& operator=(const CacheEntry&);
156
157 sp<Blob> getKey() const;
158 sp<Blob> getValue() const;
159
160 void setValue(const sp<Blob>& value);
161
162 private:
163
164 // mKey is the key that identifies the cache entry.
165 sp<Blob> mKey;
166
167 // mValue is the cached data associated with the key.
168 sp<Blob> mValue;
169 };
170
171 // A Header is the header for the entire BlobCache serialization format. No
172 // need to make this portable, so we simply write the struct out.
173 struct Header {
174 // mMagicNumber is the magic number that identifies the data as
175 // serialized BlobCache contents. It must always contain 'Blb$'.
176 uint32_t mMagicNumber;
177
178 // mBlobCacheVersion is the serialization format version.
179 uint32_t mBlobCacheVersion;
180
181 // mDeviceVersion is the device-specific version of the cache. This can
182 // be used to invalidate the cache.
183 uint32_t mDeviceVersion;
184
185 // mNumEntries is number of cache entries following the header in the
186 // data.
187 size_t mNumEntries;
188
189 // mBuildId is the build id of the device when the cache was created.
190 // When an update to the build happens (via an OTA or other update) this
191 // is used to invalidate the cache.
192 int mBuildIdLength;
193 char mBuildId[];
194 };
195
196 // An EntryHeader is the header for a serialized cache entry. No need to
197 // make this portable, so we simply write the struct out. Each EntryHeader
198 // is followed imediately by the key data and then the value data.
199 //
200 // The beginning of each serialized EntryHeader is 4-byte aligned, so the
201 // number of bytes that a serialized cache entry will occupy is:
202 //
203 // ((sizeof(EntryHeader) + keySize + valueSize) + 3) & ~3
204 //
205 struct EntryHeader {
206 // mKeySize is the size of the entry key in bytes.
207 size_t mKeySize;
208
209 // mValueSize is the size of the entry value in bytes.
210 size_t mValueSize;
211
212 // mData contains both the key and value data for the cache entry. The
213 // key comes first followed immediately by the value.
214 uint8_t mData[];
215 };
216
217 // mMaxKeySize is the maximum key size that will be cached. Calls to
218 // BlobCache::set with a keySize parameter larger than mMaxKeySize will
219 // simply not add the key/value pair to the cache.
220 const size_t mMaxKeySize;
221
222 // mMaxValueSize is the maximum value size that will be cached. Calls to
223 // BlobCache::set with a valueSize parameter larger than mMaxValueSize will
224 // simply not add the key/value pair to the cache.
225 const size_t mMaxValueSize;
226
227 // mMaxTotalSize is the maximum size that all cache entries can occupy. This
228 // includes space for both keys and values. When a call to BlobCache::set
229 // would otherwise cause this limit to be exceeded, either the key/value
230 // pair passed to BlobCache::set will not be cached or other cache entries
231 // will be evicted from the cache to make room for the new entry.
232 const size_t mMaxTotalSize;
233
234 // mTotalSize is the total combined size of all keys and values currently in
235 // the cache.
236 size_t mTotalSize;
237
238 // mRandState is the pseudo-random number generator state. It is passed to
239 // nrand48 to generate random numbers when needed.
240 unsigned short mRandState[3];
241
242 // mCacheEntries stores all the cache entries that are resident in memory.
243 // Cache entries are added to it by the 'set' method.
244 SortedVector<CacheEntry> mCacheEntries;
245};
246
247}
248
249#endif // ANDROID_BLOB_CACHE_H
diff --git a/include/utils/ByteOrder.h b/include/utils/ByteOrder.h
deleted file mode 100644
index 44ea13df8..000000000
--- a/include/utils/ByteOrder.h
+++ /dev/null
@@ -1,81 +0,0 @@
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18
19#ifndef _LIBS_UTILS_BYTE_ORDER_H
20#define _LIBS_UTILS_BYTE_ORDER_H
21
22#include <stdint.h>
23#include <sys/types.h>
24#if defined(_WIN32)
25#include <winsock2.h>
26#else
27#include <netinet/in.h>
28#endif
29
30/*
31 * These macros are like the hton/ntoh byte swapping macros,
32 * except they allow you to swap to and from the "device" byte
33 * order. The device byte order is the endianness of the target
34 * device -- for the ARM CPUs we use today, this is little endian.
35 *
36 * Note that the byte swapping functions have not been optimized
37 * much; performance is currently not an issue for them since the
38 * intent is to allow us to avoid byte swapping on the device.
39 */
40
41static inline uint32_t android_swap_long(uint32_t v)
42{
43 return (v<<24) | ((v<<8)&0x00FF0000) | ((v>>8)&0x0000FF00) | (v>>24);
44}
45
46static inline uint16_t android_swap_short(uint16_t v)
47{
48 return (v<<8) | (v>>8);
49}
50
51#define DEVICE_BYTE_ORDER LITTLE_ENDIAN
52
53#if BYTE_ORDER == DEVICE_BYTE_ORDER
54
55#define dtohl(x) (x)
56#define dtohs(x) (x)
57#define htodl(x) (x)
58#define htods(x) (x)
59
60#else
61
62#define dtohl(x) (android_swap_long(x))
63#define dtohs(x) (android_swap_short(x))
64#define htodl(x) (android_swap_long(x))
65#define htods(x) (android_swap_short(x))
66
67#endif
68
69#if BYTE_ORDER == LITTLE_ENDIAN
70#define fromlel(x) (x)
71#define fromles(x) (x)
72#define tolel(x) (x)
73#define toles(x) (x)
74#else
75#define fromlel(x) (android_swap_long(x))
76#define fromles(x) (android_swap_short(x))
77#define tolel(x) (android_swap_long(x))
78#define toles(x) (android_swap_short(x))
79#endif
80
81#endif // _LIBS_UTILS_BYTE_ORDER_H
diff --git a/include/utils/CallStack.h b/include/utils/CallStack.h
deleted file mode 100644
index 27e89f462..000000000
--- a/include/utils/CallStack.h
+++ /dev/null
@@ -1,72 +0,0 @@
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_CALLSTACK_H
18#define ANDROID_CALLSTACK_H
19
20#include <android/log.h>
21#include <backtrace/backtrace_constants.h>
22#include <utils/String8.h>
23#include <utils/Vector.h>
24
25#include <stdint.h>
26#include <sys/types.h>
27
28namespace android {
29
30class Printer;
31
32// Collect/print the call stack (function, file, line) traces for a single thread.
33class CallStack {
34public:
35 // Create an empty call stack. No-op.
36 CallStack();
37 // Create a callstack with the current thread's stack trace.
38 // Immediately dump it to logcat using the given logtag.
39 CallStack(const char* logtag, int32_t ignoreDepth=1);
40 ~CallStack();
41
42 // Reset the stack frames (same as creating an empty call stack).
43 void clear() { mFrameLines.clear(); }
44
45 // Immediately collect the stack traces for the specified thread.
46 // The default is to dump the stack of the current call.
47 void update(int32_t ignoreDepth=1, pid_t tid=BACKTRACE_CURRENT_THREAD);
48
49 // Dump a stack trace to the log using the supplied logtag.
50 void log(const char* logtag,
51 android_LogPriority priority = ANDROID_LOG_DEBUG,
52 const char* prefix = 0) const;
53
54 // Dump a stack trace to the specified file descriptor.
55 void dump(int fd, int indent = 0, const char* prefix = 0) const;
56
57 // Return a string (possibly very long) containing the complete stack trace.
58 String8 toString(const char* prefix = 0) const;
59
60 // Dump a serialized representation of the stack trace to the specified printer.
61 void print(Printer& printer) const;
62
63 // Get the count of stack frames that are in this call stack.
64 size_t size() const { return mFrameLines.size(); }
65
66private:
67 Vector<String8> mFrameLines;
68};
69
70}; // namespace android
71
72#endif // ANDROID_CALLSTACK_H
diff --git a/include/utils/Compat.h b/include/utils/Compat.h
deleted file mode 100644
index 2709e3b32..000000000
--- a/include/utils/Compat.h
+++ /dev/null
@@ -1,83 +0,0 @@
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef __LIB_UTILS_COMPAT_H
18#define __LIB_UTILS_COMPAT_H
19
20#include <unistd.h>
21
22#if defined(__APPLE__)
23
24/* Mac OS has always had a 64-bit off_t, so it doesn't have off64_t. */
25
26typedef off_t off64_t;
27
28static inline off64_t lseek64(int fd, off64_t offset, int whence) {
29 return lseek(fd, offset, whence);
30}
31
32static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset) {
33 return pread(fd, buf, nbytes, offset);
34}
35
36static inline ssize_t pwrite64(int fd, const void* buf, size_t nbytes, off64_t offset) {
37 return pwrite(fd, buf, nbytes, offset);
38}
39
40#endif /* __APPLE__ */
41
42#if defined(_WIN32)
43#define O_CLOEXEC O_NOINHERIT
44#define O_NOFOLLOW 0
45#define DEFFILEMODE 0666
46#endif /* _WIN32 */
47
48#define ZD "%zd"
49#define ZD_TYPE ssize_t
50
51/*
52 * Needed for cases where something should be constexpr if possible, but not
53 * being constexpr is fine if in pre-C++11 code (such as a const static float
54 * member variable).
55 */
56#if __cplusplus >= 201103L
57#define CONSTEXPR constexpr
58#else
59#define CONSTEXPR
60#endif
61
62/*
63 * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
64 * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
65 * not already defined, then define it here.
66 */
67#ifndef TEMP_FAILURE_RETRY
68/* Used to retry syscalls that can return EINTR. */
69#define TEMP_FAILURE_RETRY(exp) ({ \
70 typeof (exp) _rc; \
71 do { \
72 _rc = (exp); \
73 } while (_rc == -1 && errno == EINTR); \
74 _rc; })
75#endif
76
77#if defined(_WIN32)
78#define OS_PATH_SEPARATOR '\\'
79#else
80#define OS_PATH_SEPARATOR '/'
81#endif
82
83#endif /* __LIB_UTILS_COMPAT_H */
diff --git a/include/utils/Condition.h b/include/utils/Condition.h
deleted file mode 100644
index 25a53aa23..000000000
--- a/include/utils/Condition.h
+++ /dev/null
@@ -1,165 +0,0 @@
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _LIBS_UTILS_CONDITION_H
18#define _LIBS_UTILS_CONDITION_H
19
20#include <limits.h>
21#include <stdint.h>
22#include <sys/types.h>
23#include <time.h>
24
25#if !defined(_WIN32)
26# include <pthread.h>
27#endif
28
29#include <utils/Errors.h>
30#include <utils/Mutex.h>
31#include <utils/Timers.h>
32
33// ---------------------------------------------------------------------------
34namespace android {
35// ---------------------------------------------------------------------------
36
37/*
38 * Condition variable class. The implementation is system-dependent.
39 *
40 * Condition variables are paired up with mutexes. Lock the mutex,
41 * call wait(), then either re-wait() if things aren't quite what you want,
42 * or unlock the mutex and continue. All threads calling wait() must
43 * use the same mutex for a given Condition.
44 */
45class Condition {
46public:
47 enum {
48 PRIVATE = 0,
49 SHARED = 1
50 };
51
52 enum WakeUpType {
53 WAKE_UP_ONE = 0,
54 WAKE_UP_ALL = 1
55 };
56
57 Condition();
58 explicit Condition(int type);
59 ~Condition();
60 // Wait on the condition variable. Lock the mutex before calling.
61 status_t wait(Mutex& mutex);
62 // same with relative timeout
63 status_t waitRelative(Mutex& mutex, nsecs_t reltime);
64 // Signal the condition variable, allowing exactly one thread to continue.
65 void signal();
66 // Signal the condition variable, allowing one or all threads to continue.
67 void signal(WakeUpType type) {
68 if (type == WAKE_UP_ONE) {
69 signal();
70 } else {
71 broadcast();
72 }
73 }
74 // Signal the condition variable, allowing all threads to continue.
75 void broadcast();
76
77private:
78#if !defined(_WIN32)
79 pthread_cond_t mCond;
80#else
81 void* mState;
82#endif
83};
84
85// ---------------------------------------------------------------------------
86
87#if !defined(_WIN32)
88
89inline Condition::Condition() {
90 pthread_cond_init(&mCond, NULL);
91}
92inline Condition::Condition(int type) {
93 if (type == SHARED) {
94 pthread_condattr_t attr;
95 pthread_condattr_init(&attr);
96 pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
97 pthread_cond_init(&mCond, &attr);
98 pthread_condattr_destroy(&attr);
99 } else {
100 pthread_cond_init(&mCond, NULL);
101 }
102}
103inline Condition::~Condition() {
104 pthread_cond_destroy(&mCond);
105}
106inline status_t Condition::wait(Mutex& mutex) {
107 return -pthread_cond_wait(&mCond, &mutex.mMutex);
108}
109inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
110 struct timespec ts;
111#if defined(__linux__)
112 clock_gettime(CLOCK_REALTIME, &ts);
113#else // __APPLE__
114 // Apple doesn't support POSIX clocks.
115 struct timeval t;
116 gettimeofday(&t, NULL);
117 ts.tv_sec = t.tv_sec;
118 ts.tv_nsec = t.tv_usec*1000;
119#endif
120
121 // On 32-bit devices, tv_sec is 32-bit, but `reltime` is 64-bit.
122 int64_t reltime_sec = reltime/1000000000;
123
124 ts.tv_nsec += static_cast<long>(reltime%1000000000);
125 if (reltime_sec < INT64_MAX && ts.tv_nsec >= 1000000000) {
126 ts.tv_nsec -= 1000000000;
127 ++reltime_sec;
128 }
129
130 int64_t time_sec = ts.tv_sec;
131 if (time_sec > INT64_MAX - reltime_sec) {
132 time_sec = INT64_MAX;
133 } else {
134 time_sec += reltime_sec;
135 }
136
137 ts.tv_sec = (time_sec > LONG_MAX) ? LONG_MAX : static_cast<long>(time_sec);
138
139 return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
140}
141inline void Condition::signal() {
142 /*
143 * POSIX says pthread_cond_signal wakes up "one or more" waiting threads.
144 * However bionic follows the glibc guarantee which wakes up "exactly one"
145 * waiting thread.
146 *
147 * man 3 pthread_cond_signal
148 * pthread_cond_signal restarts one of the threads that are waiting on
149 * the condition variable cond. If no threads are waiting on cond,
150 * nothing happens. If several threads are waiting on cond, exactly one
151 * is restarted, but it is not specified which.
152 */
153 pthread_cond_signal(&mCond);
154}
155inline void Condition::broadcast() {
156 pthread_cond_broadcast(&mCond);
157}
158
159#endif // !defined(_WIN32)
160
161// ---------------------------------------------------------------------------
162}; // namespace android
163// ---------------------------------------------------------------------------
164
165#endif // _LIBS_UTILS_CONDITON_H
diff --git a/include/utils/Debug.h b/include/utils/Debug.h
deleted file mode 100644
index 08893bdaa..000000000
--- a/include/utils/Debug.h
+++ /dev/null
@@ -1,48 +0,0 @@
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_UTILS_DEBUG_H
18#define ANDROID_UTILS_DEBUG_H
19
20#include <stdint.h>
21#include <sys/types.h>
22
23namespace android {
24// ---------------------------------------------------------------------------
25
26#ifdef __cplusplus
27template<bool> struct CompileTimeAssert;
28template<> struct CompileTimeAssert<true> {};
29#define COMPILE_TIME_ASSERT(_exp) \
30 template class CompileTimeAssert< (_exp) >;
31#endif
32#define COMPILE_TIME_ASSERT_FUNCTION_SCOPE(_exp) \
33 CompileTimeAssert<( _exp )>();
34
35// ---------------------------------------------------------------------------
36
37#ifdef __cplusplus
38template<bool C, typename LSH, typename RHS> struct CompileTimeIfElse;
39template<typename LHS, typename RHS>
40struct CompileTimeIfElse<true, LHS, RHS> { typedef LHS TYPE; };
41template<typename LHS, typename RHS>
42struct CompileTimeIfElse<false, LHS, RHS> { typedef RHS TYPE; };
43#endif
44
45// ---------------------------------------------------------------------------
46}; // namespace android
47
48#endif // ANDROID_UTILS_DEBUG_H
diff --git a/include/utils/Endian.h b/include/utils/Endian.h
deleted file mode 100644
index 591cae0d3..000000000
--- a/include/utils/Endian.h
+++ /dev/null
@@ -1,35 +0,0 @@
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// Android endian-ness defines.
19//
20#ifndef _LIBS_UTILS_ENDIAN_H
21#define _LIBS_UTILS_ENDIAN_H
22
23#if defined(__APPLE__) || defined(_WIN32)
24
25#define __BIG_ENDIAN 0x1000
26#define __LITTLE_ENDIAN 0x0001
27#define __BYTE_ORDER __LITTLE_ENDIAN
28
29#else
30
31#include <endian.h>
32
33#endif
34
35#endif /*_LIBS_UTILS_ENDIAN_H*/
diff --git a/include/utils/Errors.h b/include/utils/Errors.h
deleted file mode 100644
index 16e1fa2c2..000000000
--- a/include/utils/Errors.h
+++ /dev/null
@@ -1,88 +0,0 @@
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_ERRORS_H
18#define ANDROID_ERRORS_H
19
20#include <sys/types.h>
21#include <errno.h>
22
23namespace android {
24
25// use this type to return error codes
26#ifdef _WIN32
27typedef int status_t;
28#else
29typedef int32_t status_t;
30#endif
31
32/* the MS C runtime lacks a few error codes */
33
34/*
35 * Error codes.
36 * All error codes are negative values.
37 */
38
39// Win32 #defines NO_ERROR as well. It has the same value, so there's no
40// real conflict, though it's a bit awkward.
41#ifdef _WIN32
42# undef NO_ERROR
43#endif
44
45enum {
46 OK = 0, // Everything's swell.
47 NO_ERROR = 0, // No errors.
48
49 UNKNOWN_ERROR = (-2147483647-1), // INT32_MIN value
50
51 NO_MEMORY = -ENOMEM,
52 INVALID_OPERATION = -ENOSYS,
53 BAD_VALUE = -EINVAL,
54 BAD_TYPE = (UNKNOWN_ERROR + 1),
55 NAME_NOT_FOUND = -ENOENT,
56 PERMISSION_DENIED = -EPERM,
57 NO_INIT = -ENODEV,
58 ALREADY_EXISTS = -EEXIST,
59 DEAD_OBJECT = -EPIPE,
60 FAILED_TRANSACTION = (UNKNOWN_ERROR + 2),
61#if !defined(_WIN32)
62 BAD_INDEX = -EOVERFLOW,
63 NOT_ENOUGH_DATA = -ENODATA,
64 WOULD_BLOCK = -EWOULDBLOCK,
65 TIMED_OUT = -ETIMEDOUT,
66 UNKNOWN_TRANSACTION = -EBADMSG,
67#else
68 BAD_INDEX = -E2BIG,
69 NOT_ENOUGH_DATA = (UNKNOWN_ERROR + 3),
70 WOULD_BLOCK = (UNKNOWN_ERROR + 4),
71 TIMED_OUT = (UNKNOWN_ERROR + 5),
72 UNKNOWN_TRANSACTION = (UNKNOWN_ERROR + 6),
73#endif
74 FDS_NOT_ALLOWED = (UNKNOWN_ERROR + 7),
75 UNEXPECTED_NULL = (UNKNOWN_ERROR + 8),
76};
77
78// Restore define; enumeration is in "android" namespace, so the value defined
79// there won't work for Win32 code in a different namespace.
80#ifdef _WIN32
81# define NO_ERROR 0L
82#endif
83
84}; // namespace android
85
86// ---------------------------------------------------------------------------
87
88#endif // ANDROID_ERRORS_H
diff --git a/include/utils/FastStrcmp.h b/include/utils/FastStrcmp.h
deleted file mode 100644
index 3844e7d96..000000000
--- a/include/utils/FastStrcmp.h
+++ /dev/null
@@ -1,54 +0,0 @@
1/*
2 * Copyright (C) 2014-2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _ANDROID_UTILS_FASTSTRCMP_H__
18#define _ANDROID_UTILS_FASTSTRCMP_H__
19
20#ifdef __cplusplus
21
22// Optimized for instruction cache locality
23//
24// Template class fastcmp used to create more time-efficient str*cmp
25// functions by pre-checking the first character before resorting
26// to calling the underlying string function. Profiled with a
27// measurable speedup when used in hot code. Usage is of the form:
28//
29// fastcmp<strncmp>(str1, str2, len)
30//
31// NB: Does not work for the case insensitive str*cmp functions.
32// NB: Returns boolean, do not use if expecting to check negative value.
33// Thus not semantically identical to the expected function behavior.
34
35template <int (*cmp)(const char *l, const char *r, const size_t s)>
36static inline int fastcmp(const char *l, const char *r, const size_t s) {
37 return (*l != *r) || cmp(l + 1, r + 1, s - 1);
38}
39
40template <int (*cmp)(const void *l, const void *r, const size_t s)>
41static inline int fastcmp(const void *lv, const void *rv, const size_t s) {
42 const char *l = static_cast<const char *>(lv);
43 const char *r = static_cast<const char *>(rv);
44 return (*l != *r) || cmp(l + 1, r + 1, s - 1);
45}
46
47template <int (*cmp)(const char *l, const char *r)>
48static inline int fastcmp(const char *l, const char *r) {
49 return (*l != *r) || cmp(l + 1, r + 1);
50}
51
52#endif
53
54#endif // _ANDROID_UTILS_FASTSTRCMP_H__
diff --git a/include/utils/FileMap.h b/include/utils/FileMap.h
deleted file mode 100644
index 7d372e1dc..000000000
--- a/include/utils/FileMap.h
+++ /dev/null
@@ -1,129 +0,0 @@
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// Encapsulate a shared file mapping.
19//
20#ifndef __LIBS_FILE_MAP_H
21#define __LIBS_FILE_MAP_H
22
23#include <sys/types.h>
24
25#include <utils/Compat.h>
26
27#if defined(__MINGW32__)
28// Ensure that we always pull in winsock2.h before windows.h
29#if defined(_WIN32)
30#include <winsock2.h>
31#endif
32#include <windows.h>
33#endif
34
35namespace android {
36
37/*
38 * This represents a memory-mapped file. It might be the entire file or
39 * only part of it. This requires a little bookkeeping because the mapping
40 * needs to be aligned on page boundaries, and in some cases we'd like to
41 * have multiple references to the mapped area without creating additional
42 * maps.
43 *
44 * This always uses MAP_SHARED.
45 *
46 * TODO: we should be able to create a new FileMap that is a subset of
47 * an existing FileMap and shares the underlying mapped pages. Requires
48 * completing the refcounting stuff and possibly introducing the notion
49 * of a FileMap hierarchy.
50 */
51class FileMap {
52public:
53 FileMap(void);
54
55 FileMap(FileMap&& f);
56 FileMap& operator=(FileMap&& f);
57
58 /*
59 * Create a new mapping on an open file.
60 *
61 * Closing the file descriptor does not unmap the pages, so we don't
62 * claim ownership of the fd.
63 *
64 * Returns "false" on failure.
65 */
66 bool create(const char* origFileName, int fd,
67 off64_t offset, size_t length, bool readOnly);
68
69 ~FileMap(void);
70
71 /*
72 * Return the name of the file this map came from, if known.
73 */
74 const char* getFileName(void) const { return mFileName; }
75
76 /*
77 * Get a pointer to the piece of the file we requested.
78 */
79 void* getDataPtr(void) const { return mDataPtr; }
80
81 /*
82 * Get the length we requested.
83 */
84 size_t getDataLength(void) const { return mDataLength; }
85
86 /*
87 * Get the data offset used to create this map.
88 */
89 off64_t getDataOffset(void) const { return mDataOffset; }
90
91 /*
92 * This maps directly to madvise() values, but allows us to avoid
93 * including <sys/mman.h> everywhere.
94 */
95 enum MapAdvice {
96 NORMAL, RANDOM, SEQUENTIAL, WILLNEED, DONTNEED
97 };
98
99 /*
100 * Apply an madvise() call to the entire file.
101 *
102 * Returns 0 on success, -1 on failure.
103 */
104 int advise(MapAdvice advice);
105
106protected:
107
108private:
109 // these are not implemented
110 FileMap(const FileMap& src);
111 const FileMap& operator=(const FileMap& src);
112
113 char* mFileName; // original file name, if known
114 void* mBasePtr; // base of mmap area; page aligned
115 size_t mBaseLength; // length, measured from "mBasePtr"
116 off64_t mDataOffset; // offset used when map was created
117 void* mDataPtr; // start of requested data, offset from base
118 size_t mDataLength; // length, measured from "mDataPtr"
119#if defined(__MINGW32__)
120 HANDLE mFileHandle; // Win32 file handle
121 HANDLE mFileMapping; // Win32 file mapping handle
122#endif
123
124 static long mPageSize;
125};
126
127}; // namespace android
128
129#endif // __LIBS_FILE_MAP_H
diff --git a/include/utils/Flattenable.h b/include/utils/Flattenable.h
deleted file mode 100644
index 22b811a14..000000000
--- a/include/utils/Flattenable.h
+++ /dev/null
@@ -1,205 +0,0 @@
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_UTILS_FLATTENABLE_H
18#define ANDROID_UTILS_FLATTENABLE_H
19
20
21#include <stdint.h>
22#include <string.h>
23#include <sys/types.h>
24#include <utils/Errors.h>
25#include <utils/Debug.h>
26
27#include <type_traits>
28
29namespace android {
30
31
32class FlattenableUtils {
33public:
34 template<size_t N>
35 static size_t align(size_t size) {
36 COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
37 return (size + (N-1)) & ~(N-1);
38 }
39
40 template<size_t N>
41 static size_t align(void const*& buffer) {
42 COMPILE_TIME_ASSERT_FUNCTION_SCOPE( !(N & (N-1)) );
43 uintptr_t b = uintptr_t(buffer);
44 buffer = reinterpret_cast<void*>((uintptr_t(buffer) + (N-1)) & ~(N-1));
45 return size_t(uintptr_t(buffer) - b);
46 }
47
48 template<size_t N>
49 static size_t align(void*& buffer) {
50 return align<N>( const_cast<void const*&>(buffer) );
51 }
52
53 static void advance(void*& buffer, size_t& size, size_t offset) {
54 buffer = reinterpret_cast<void*>( uintptr_t(buffer) + offset );
55 size -= offset;
56 }
57
58 static void advance(void const*& buffer, size_t& size, size_t offset) {
59 buffer = reinterpret_cast<void const*>( uintptr_t(buffer) + offset );
60 size -= offset;
61 }
62
63 // write a POD structure
64 template<typename T>
65 static void write(void*& buffer, size_t& size, const T& value) {
66 static_assert(std::is_trivially_copyable<T>::value,
67 "Cannot flatten a non-trivially-copyable type");
68 memcpy(buffer, &value, sizeof(T));
69 advance(buffer, size, sizeof(T));
70 }
71
72 // read a POD structure
73 template<typename T>
74 static void read(void const*& buffer, size_t& size, T& value) {
75 static_assert(std::is_trivially_copyable<T>::value,
76 "Cannot unflatten a non-trivially-copyable type");
77 memcpy(&value, buffer, sizeof(T));
78 advance(buffer, size, sizeof(T));
79 }
80};
81
82
83/*
84 * The Flattenable protocol allows an object to serialize itself out
85 * to a byte-buffer and an array of file descriptors.
86 * Flattenable objects must implement this protocol.
87 */
88
89template <typename T>
90class Flattenable {
91public:
92 // size in bytes of the flattened object
93 inline size_t getFlattenedSize() const;
94
95 // number of file descriptors to flatten
96 inline size_t getFdCount() const;
97
98 // flattens the object into buffer.
99 // size should be at least of getFlattenedSize()
100 // file descriptors are written in the fds[] array but ownership is
101 // not transfered (ie: they must be dupped by the caller of
102 // flatten() if needed).
103 inline status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
104
105 // unflattens the object from buffer.
106 // size should be equal to the value of getFlattenedSize() when the
107 // object was flattened.
108 // unflattened file descriptors are found in the fds[] array and
109 // don't need to be dupped(). ie: the caller of unflatten doesn't
110 // keep ownership. If a fd is not retained by unflatten() it must be
111 // explicitly closed.
112 inline status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
113};
114
115template<typename T>
116inline size_t Flattenable<T>::getFlattenedSize() const {
117 return static_cast<T const*>(this)->T::getFlattenedSize();
118}
119template<typename T>
120inline size_t Flattenable<T>::getFdCount() const {
121 return static_cast<T const*>(this)->T::getFdCount();
122}
123template<typename T>
124inline status_t Flattenable<T>::flatten(
125 void*& buffer, size_t& size, int*& fds, size_t& count) const {
126 return static_cast<T const*>(this)->T::flatten(buffer, size, fds, count);
127}
128template<typename T>
129inline status_t Flattenable<T>::unflatten(
130 void const*& buffer, size_t& size, int const*& fds, size_t& count) {
131 return static_cast<T*>(this)->T::unflatten(buffer, size, fds, count);
132}
133
134/*
135 * LightFlattenable is a protocol allowing object to serialize themselves out
136 * to a byte-buffer. Because it doesn't handle file-descriptors,
137 * LightFlattenable is usually more size efficient than Flattenable.
138 * LightFlattenable objects must implement this protocol.
139 */
140template <typename T>
141class LightFlattenable {
142public:
143 // returns whether this object always flatten into the same size.
144 // for efficiency, this should always be inline.
145 inline bool isFixedSize() const;
146
147 // returns size in bytes of the flattened object. must be a constant.
148 inline size_t getFlattenedSize() const;
149
150 // flattens the object into buffer.
151 inline status_t flatten(void* buffer, size_t size) const;
152
153 // unflattens the object from buffer of given size.
154 inline status_t unflatten(void const* buffer, size_t size);
155};
156
157template <typename T>
158inline bool LightFlattenable<T>::isFixedSize() const {
159 return static_cast<T const*>(this)->T::isFixedSize();
160}
161template <typename T>
162inline size_t LightFlattenable<T>::getFlattenedSize() const {
163 return static_cast<T const*>(this)->T::getFlattenedSize();
164}
165template <typename T>
166inline status_t LightFlattenable<T>::flatten(void* buffer, size_t size) const {
167 return static_cast<T const*>(this)->T::flatten(buffer, size);
168}
169template <typename T>
170inline status_t LightFlattenable<T>::unflatten(void const* buffer, size_t size) {
171 return static_cast<T*>(this)->T::unflatten(buffer, size);
172}
173
174/*
175 * LightFlattenablePod is an implementation of the LightFlattenable protocol
176 * for POD (plain-old-data) objects.
177 * Simply derive from LightFlattenablePod<Foo> to make Foo flattenable; no
178 * need to implement any methods; obviously Foo must be a POD structure.
179 */
180template <typename T>
181class LightFlattenablePod : public LightFlattenable<T> {
182public:
183 inline bool isFixedSize() const {
184 return true;
185 }
186
187 inline size_t getFlattenedSize() const {
188 return sizeof(T);
189 }
190 inline status_t flatten(void* buffer, size_t size) const {
191 if (size < sizeof(T)) return NO_MEMORY;
192 *reinterpret_cast<T*>(buffer) = *static_cast<T const*>(this);
193 return NO_ERROR;
194 }
195 inline status_t unflatten(void const* buffer, size_t) {
196 *static_cast<T*>(this) = *reinterpret_cast<T const*>(buffer);
197 return NO_ERROR;
198 }
199};
200
201
202}; // namespace android
203
204
205#endif /* ANDROID_UTILS_FLATTENABLE_H */
diff --git a/include/utils/Functor.h b/include/utils/Functor.h
deleted file mode 100644
index 09ea614b6..000000000
--- a/include/utils/Functor.h
+++ /dev/null
@@ -1,33 +0,0 @@
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_FUNCTOR_H
18#define ANDROID_FUNCTOR_H
19
20#include <utils/Errors.h>
21
22namespace android {
23
24class Functor {
25public:
26 Functor() {}
27 virtual ~Functor() {}
28 virtual status_t operator ()(int /*what*/, void* /*data*/) { return NO_ERROR; }
29};
30
31}; // namespace android
32
33#endif // ANDROID_FUNCTOR_H
diff --git a/include/utils/JenkinsHash.h b/include/utils/JenkinsHash.h
deleted file mode 100644
index 027c10c7e..000000000
--- a/include/utils/JenkinsHash.h
+++ /dev/null
@@ -1,51 +0,0 @@
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* Implementation of Jenkins one-at-a-time hash function. These choices are
18 * optimized for code size and portability, rather than raw speed. But speed
19 * should still be quite good.
20 **/
21
22#ifndef ANDROID_JENKINS_HASH_H
23#define ANDROID_JENKINS_HASH_H
24
25#include <utils/TypeHelpers.h>
26
27namespace android {
28
29/* The Jenkins hash of a sequence of 32 bit words A, B, C is:
30 * Whiten(Mix(Mix(Mix(0, A), B), C)) */
31
32#ifdef __clang__
33__attribute__((no_sanitize("integer")))
34#endif
35inline uint32_t JenkinsHashMix(uint32_t hash, uint32_t data) {
36 hash += data;
37 hash += (hash << 10);
38 hash ^= (hash >> 6);
39 return hash;
40}
41
42hash_t JenkinsHashWhiten(uint32_t hash);
43
44/* Helpful utility functions for hashing data in 32 bit chunks */
45uint32_t JenkinsHashMixBytes(uint32_t hash, const uint8_t* bytes, size_t size);
46
47uint32_t JenkinsHashMixShorts(uint32_t hash, const uint16_t* shorts, size_t size);
48
49}
50
51#endif // ANDROID_JENKINS_HASH_H
diff --git a/include/utils/KeyedVector.h b/include/utils/KeyedVector.h
deleted file mode 100644
index f93ad6e21..000000000
--- a/include/utils/KeyedVector.h
+++ /dev/null
@@ -1,216 +0,0 @@
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_KEYED_VECTOR_H
18#define ANDROID_KEYED_VECTOR_H
19
20#include <assert.h>
21#include <stdint.h>
22#include <sys/types.h>
23
24#include <log/log.h>
25#include <utils/Errors.h>
26#include <utils/SortedVector.h>
27#include <utils/TypeHelpers.h>
28
29// ---------------------------------------------------------------------------
30
31namespace android {
32
33template <typename KEY, typename VALUE>
34class KeyedVector
35{
36public:
37 typedef KEY key_type;
38 typedef VALUE value_type;
39
40 inline KeyedVector();
41
42 /*
43 * empty the vector
44 */
45
46 inline void clear() { mVector.clear(); }
47
48 /*!
49 * vector stats
50 */
51
52 //! returns number of items in the vector
53 inline size_t size() const { return mVector.size(); }
54 //! returns whether or not the vector is empty
55 inline bool isEmpty() const { return mVector.isEmpty(); }
56 //! returns how many items can be stored without reallocating the backing store
57 inline size_t capacity() const { return mVector.capacity(); }
58 //! sets the capacity. capacity can never be reduced less than size()
59 inline ssize_t setCapacity(size_t size) { return mVector.setCapacity(size); }
60
61 // returns true if the arguments is known to be identical to this vector
62 inline bool isIdenticalTo(const KeyedVector& rhs) const;
63
64 /*!
65 * accessors
66 */
67 const VALUE& valueFor(const KEY& key) const;
68 const VALUE& valueAt(size_t index) const;
69 const KEY& keyAt(size_t index) const;
70 ssize_t indexOfKey(const KEY& key) const;
71 const VALUE& operator[] (size_t index) const;
72
73 /*!
74 * modifying the array
75 */
76
77 VALUE& editValueFor(const KEY& key);
78 VALUE& editValueAt(size_t index);
79
80 /*!
81 * add/insert/replace items
82 */
83
84 ssize_t add(const KEY& key, const VALUE& item);
85 ssize_t replaceValueFor(const KEY& key, const VALUE& item);
86 ssize_t replaceValueAt(size_t index, const VALUE& item);
87
88 /*!
89 * remove items
90 */
91
92 ssize_t removeItem(const KEY& key);
93 ssize_t removeItemsAt(size_t index, size_t count = 1);
94
95private:
96 SortedVector< key_value_pair_t<KEY, VALUE> > mVector;
97};
98
99// ---------------------------------------------------------------------------
100
101/**
102 * Variation of KeyedVector that holds a default value to return when
103 * valueFor() is called with a key that doesn't exist.
104 */
105template <typename KEY, typename VALUE>
106class DefaultKeyedVector : public KeyedVector<KEY, VALUE>
107{
108public:
109 inline DefaultKeyedVector(const VALUE& defValue = VALUE());
110 const VALUE& valueFor(const KEY& key) const;
111
112private:
113 VALUE mDefault;
114};
115
116// ---------------------------------------------------------------------------
117
118template<typename KEY, typename VALUE> inline
119KeyedVector<KEY,VALUE>::KeyedVector()
120{
121}
122
123template<typename KEY, typename VALUE> inline
124bool KeyedVector<KEY,VALUE>::isIdenticalTo(const KeyedVector<KEY,VALUE>& rhs) const {
125 return mVector.array() == rhs.mVector.array();
126}
127
128template<typename KEY, typename VALUE> inline
129ssize_t KeyedVector<KEY,VALUE>::indexOfKey(const KEY& key) const {
130 return mVector.indexOf( key_value_pair_t<KEY,VALUE>(key) );
131}
132
133template<typename KEY, typename VALUE> inline
134const VALUE& KeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
135 ssize_t i = this->indexOfKey(key);
136 LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
137 return mVector.itemAt(i).value;
138}
139
140template<typename KEY, typename VALUE> inline
141const VALUE& KeyedVector<KEY,VALUE>::valueAt(size_t index) const {
142 return mVector.itemAt(index).value;
143}
144
145template<typename KEY, typename VALUE> inline
146const VALUE& KeyedVector<KEY,VALUE>::operator[] (size_t index) const {
147 return valueAt(index);
148}
149
150template<typename KEY, typename VALUE> inline
151const KEY& KeyedVector<KEY,VALUE>::keyAt(size_t index) const {
152 return mVector.itemAt(index).key;
153}
154
155template<typename KEY, typename VALUE> inline
156VALUE& KeyedVector<KEY,VALUE>::editValueFor(const KEY& key) {
157 ssize_t i = this->indexOfKey(key);
158 LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
159 return mVector.editItemAt(static_cast<size_t>(i)).value;
160}
161
162template<typename KEY, typename VALUE> inline
163VALUE& KeyedVector<KEY,VALUE>::editValueAt(size_t index) {
164 return mVector.editItemAt(index).value;
165}
166
167template<typename KEY, typename VALUE> inline
168ssize_t KeyedVector<KEY,VALUE>::add(const KEY& key, const VALUE& value) {
169 return mVector.add( key_value_pair_t<KEY,VALUE>(key, value) );
170}
171
172template<typename KEY, typename VALUE> inline
173ssize_t KeyedVector<KEY,VALUE>::replaceValueFor(const KEY& key, const VALUE& value) {
174 key_value_pair_t<KEY,VALUE> pair(key, value);
175 mVector.remove(pair);
176 return mVector.add(pair);
177}
178
179template<typename KEY, typename VALUE> inline
180ssize_t KeyedVector<KEY,VALUE>::replaceValueAt(size_t index, const VALUE& item) {
181 if (index<size()) {
182 mVector.editItemAt(index).value = item;
183 return static_cast<ssize_t>(index);
184 }
185 return BAD_INDEX;
186}
187
188template<typename KEY, typename VALUE> inline
189ssize_t KeyedVector<KEY,VALUE>::removeItem(const KEY& key) {
190 return mVector.remove(key_value_pair_t<KEY,VALUE>(key));
191}
192
193template<typename KEY, typename VALUE> inline
194ssize_t KeyedVector<KEY, VALUE>::removeItemsAt(size_t index, size_t count) {
195 return mVector.removeItemsAt(index, count);
196}
197
198// ---------------------------------------------------------------------------
199
200template<typename KEY, typename VALUE> inline
201DefaultKeyedVector<KEY,VALUE>::DefaultKeyedVector(const VALUE& defValue)
202 : mDefault(defValue)
203{
204}
205
206template<typename KEY, typename VALUE> inline
207const VALUE& DefaultKeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
208 ssize_t i = this->indexOfKey(key);
209 return i >= 0 ? KeyedVector<KEY,VALUE>::valueAt(i) : mDefault;
210}
211
212}; // namespace android
213
214// ---------------------------------------------------------------------------
215
216#endif // ANDROID_KEYED_VECTOR_H
diff --git a/include/utils/LinearTransform.h b/include/utils/LinearTransform.h
deleted file mode 100644
index 04cb355c7..000000000
--- a/include/utils/LinearTransform.h
+++ /dev/null
@@ -1,64 +0,0 @@
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _LIBS_UTILS_LINEAR_TRANSFORM_H
18#define _LIBS_UTILS_LINEAR_TRANSFORM_H
19
20#include <stdint.h>
21
22namespace android {
23
24// LinearTransform defines a structure which hold the definition of a
25// transformation from single dimensional coordinate system A into coordinate
26// system B (and back again). Values in A and in B are 64 bit, the linear
27// scale factor is expressed as a rational number using two 32 bit values.
28//
29// Specifically, let
30// f(a) = b
31// F(b) = f^-1(b) = a
32// then
33//
34// f(a) = (((a - a_zero) * a_to_b_numer) / a_to_b_denom) + b_zero;
35//
36// and
37//
38// F(b) = (((b - b_zero) * a_to_b_denom) / a_to_b_numer) + a_zero;
39//
40struct LinearTransform {
41 int64_t a_zero;
42 int64_t b_zero;
43 int32_t a_to_b_numer;
44 uint32_t a_to_b_denom;
45
46 // Transform from A->B
47 // Returns true on success, or false in the case of a singularity or an
48 // overflow.
49 bool doForwardTransform(int64_t a_in, int64_t* b_out) const;
50
51 // Transform from B->A
52 // Returns true on success, or false in the case of a singularity or an
53 // overflow.
54 bool doReverseTransform(int64_t b_in, int64_t* a_out) const;
55
56 // Helpers which will reduce the fraction N/D using Euclid's method.
57 template <class T> static void reduce(T* N, T* D);
58 static void reduce(int32_t* N, uint32_t* D);
59};
60
61
62}
63
64#endif // _LIBS_UTILS_LINEAR_TRANSFORM_H
diff --git a/include/utils/List.h b/include/utils/List.h
deleted file mode 100644
index 403cd7f1e..000000000
--- a/include/utils/List.h
+++ /dev/null
@@ -1,332 +0,0 @@
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// Templated list class. Normally we'd use STL, but we don't have that.
19// This class mimics STL's interfaces.
20//
21// Objects are copied into the list with the '=' operator or with copy-
22// construction, so if the compiler's auto-generated versions won't work for
23// you, define your own.
24//
25// The only class you want to use from here is "List".
26//
27#ifndef _LIBS_UTILS_LIST_H
28#define _LIBS_UTILS_LIST_H
29
30#include <stddef.h>
31#include <stdint.h>
32
33namespace android {
34
35/*
36 * Doubly-linked list. Instantiate with "List<MyClass> myList".
37 *
38 * Objects added to the list are copied using the assignment operator,
39 * so this must be defined.
40 */
41template<typename T>
42class List
43{
44protected:
45 /*
46 * One element in the list.
47 */
48 class _Node {
49 public:
50 explicit _Node(const T& val) : mVal(val) {}
51 ~_Node() {}
52 inline T& getRef() { return mVal; }
53 inline const T& getRef() const { return mVal; }
54 inline _Node* getPrev() const { return mpPrev; }
55 inline _Node* getNext() const { return mpNext; }
56 inline void setVal(const T& val) { mVal = val; }
57 inline void setPrev(_Node* ptr) { mpPrev = ptr; }
58 inline void setNext(_Node* ptr) { mpNext = ptr; }
59 private:
60 friend class List;
61 friend class _ListIterator;
62 T mVal;
63 _Node* mpPrev;
64 _Node* mpNext;
65 };
66
67 /*
68 * Iterator for walking through the list.
69 */
70
71 template <typename TYPE>
72 struct CONST_ITERATOR {
73 typedef _Node const * NodePtr;
74 typedef const TYPE Type;
75 };
76
77 template <typename TYPE>
78 struct NON_CONST_ITERATOR {
79 typedef _Node* NodePtr;
80 typedef TYPE Type;
81 };
82
83 template<
84 typename U,
85 template <class> class Constness
86 >
87 class _ListIterator {
88 typedef _ListIterator<U, Constness> _Iter;
89 typedef typename Constness<U>::NodePtr _NodePtr;
90 typedef typename Constness<U>::Type _Type;
91
92 explicit _ListIterator(_NodePtr ptr) : mpNode(ptr) {}
93
94 public:
95 _ListIterator() {}
96 _ListIterator(const _Iter& rhs) : mpNode(rhs.mpNode) {}
97 ~_ListIterator() {}
98
99 // this will handle conversions from iterator to const_iterator
100 // (and also all convertible iterators)
101 // Here, in this implementation, the iterators can be converted
102 // if the nodes can be converted
103 template<typename V> explicit
104 _ListIterator(const V& rhs) : mpNode(rhs.mpNode) {}
105
106
107 /*
108 * Dereference operator. Used to get at the juicy insides.
109 */
110 _Type& operator*() const { return mpNode->getRef(); }
111 _Type* operator->() const { return &(mpNode->getRef()); }
112
113 /*
114 * Iterator comparison.
115 */
116 inline bool operator==(const _Iter& right) const {
117 return mpNode == right.mpNode; }
118
119 inline bool operator!=(const _Iter& right) const {
120 return mpNode != right.mpNode; }
121
122 /*
123 * handle comparisons between iterator and const_iterator
124 */
125 template<typename OTHER>
126 inline bool operator==(const OTHER& right) const {
127 return mpNode == right.mpNode; }
128
129 template<typename OTHER>
130 inline bool operator!=(const OTHER& right) const {
131 return mpNode != right.mpNode; }
132
133 /*
134 * Incr/decr, used to move through the list.
135 */
136 inline _Iter& operator++() { // pre-increment
137 mpNode = mpNode->getNext();
138 return *this;
139 }
140 const _Iter operator++(int) { // post-increment
141 _Iter tmp(*this);
142 mpNode = mpNode->getNext();
143 return tmp;
144 }
145 inline _Iter& operator--() { // pre-increment
146 mpNode = mpNode->getPrev();
147 return *this;
148 }
149 const _Iter operator--(int) { // post-increment
150 _Iter tmp(*this);
151 mpNode = mpNode->getPrev();
152 return tmp;
153 }
154
155 inline _NodePtr getNode() const { return mpNode; }
156
157 _NodePtr mpNode; /* should be private, but older gcc fails */
158 private:
159 friend class List;
160 };
161
162public:
163 List() {
164 prep();
165 }
166 List(const List<T>& src) { // copy-constructor
167 prep();
168 insert(begin(), src.begin(), src.end());
169 }
170 virtual ~List() {
171 clear();
172 delete[] (unsigned char*) mpMiddle;
173 }
174
175 typedef _ListIterator<T, NON_CONST_ITERATOR> iterator;
176 typedef _ListIterator<T, CONST_ITERATOR> const_iterator;
177
178 List<T>& operator=(const List<T>& right);
179
180 /* returns true if the list is empty */
181 inline bool empty() const { return mpMiddle->getNext() == mpMiddle; }
182
183 /* return #of elements in list */
184 size_t size() const {
185 return size_t(distance(begin(), end()));
186 }
187
188 /*
189 * Return the first element or one past the last element. The
190 * _Node* we're returning is converted to an "iterator" by a
191 * constructor in _ListIterator.
192 */
193 inline iterator begin() {
194 return iterator(mpMiddle->getNext());
195 }
196 inline const_iterator begin() const {
197 return const_iterator(const_cast<_Node const*>(mpMiddle->getNext()));
198 }
199 inline iterator end() {
200 return iterator(mpMiddle);
201 }
202 inline const_iterator end() const {
203 return const_iterator(const_cast<_Node const*>(mpMiddle));
204 }
205
206 /* add the object to the head or tail of the list */
207 void push_front(const T& val) { insert(begin(), val); }
208 void push_back(const T& val) { insert(end(), val); }
209
210 /* insert before the current node; returns iterator at new node */
211 iterator insert(iterator posn, const T& val)
212 {
213 _Node* newNode = new _Node(val); // alloc & copy-construct
214 newNode->setNext(posn.getNode());
215 newNode->setPrev(posn.getNode()->getPrev());
216 posn.getNode()->getPrev()->setNext(newNode);
217 posn.getNode()->setPrev(newNode);
218 return iterator(newNode);
219 }
220
221 /* insert a range of elements before the current node */
222 void insert(iterator posn, const_iterator first, const_iterator last) {
223 for ( ; first != last; ++first)
224 insert(posn, *first);
225 }
226
227 /* remove one entry; returns iterator at next node */
228 iterator erase(iterator posn) {
229 _Node* pNext = posn.getNode()->getNext();
230 _Node* pPrev = posn.getNode()->getPrev();
231 pPrev->setNext(pNext);
232 pNext->setPrev(pPrev);
233 delete posn.getNode();
234 return iterator(pNext);
235 }
236
237 /* remove a range of elements */
238 iterator erase(iterator first, iterator last) {
239 while (first != last)
240 erase(first++); // don't erase than incr later!
241 return iterator(last);
242 }
243
244 /* remove all contents of the list */
245 void clear() {
246 _Node* pCurrent = mpMiddle->getNext();
247 _Node* pNext;
248
249 while (pCurrent != mpMiddle) {
250 pNext = pCurrent->getNext();
251 delete pCurrent;
252 pCurrent = pNext;
253 }
254 mpMiddle->setPrev(mpMiddle);
255 mpMiddle->setNext(mpMiddle);
256 }
257
258 /*
259 * Measure the distance between two iterators. On exist, "first"
260 * will be equal to "last". The iterators must refer to the same
261 * list.
262 *
263 * FIXME: This is actually a generic iterator function. It should be a
264 * template function at the top-level with specializations for things like
265 * vector<>, which can just do pointer math). Here we limit it to
266 * _ListIterator of the same type but different constness.
267 */
268 template<
269 typename U,
270 template <class> class CL,
271 template <class> class CR
272 >
273 ptrdiff_t distance(
274 _ListIterator<U, CL> first, _ListIterator<U, CR> last) const
275 {
276 ptrdiff_t count = 0;
277 while (first != last) {
278 ++first;
279 ++count;
280 }
281 return count;
282 }
283
284private:
285 /*
286 * I want a _Node but don't need it to hold valid data. More
287 * to the point, I don't want T's constructor to fire, since it
288 * might have side-effects or require arguments. So, we do this
289 * slightly uncouth storage alloc.
290 */
291 void prep() {
292 mpMiddle = (_Node*) new unsigned char[sizeof(_Node)];
293 mpMiddle->setPrev(mpMiddle);
294 mpMiddle->setNext(mpMiddle);
295 }
296
297 /*
298 * This node plays the role of "pointer to head" and "pointer to tail".
299 * It sits in the middle of a circular list of nodes. The iterator
300 * runs around the circle until it encounters this one.
301 */
302 _Node* mpMiddle;
303};
304
305/*
306 * Assignment operator.
307 *
308 * The simplest way to do this would be to clear out the target list and
309 * fill it with the source. However, we can speed things along by
310 * re-using existing elements.
311 */
312template<class T>
313List<T>& List<T>::operator=(const List<T>& right)
314{
315 if (this == &right)
316 return *this; // self-assignment
317 iterator firstDst = begin();
318 iterator lastDst = end();
319 const_iterator firstSrc = right.begin();
320 const_iterator lastSrc = right.end();
321 while (firstSrc != lastSrc && firstDst != lastDst)
322 *firstDst++ = *firstSrc++;
323 if (firstSrc == lastSrc) // ran out of elements in source?
324 erase(firstDst, lastDst); // yes, erase any extras
325 else
326 insert(lastDst, firstSrc, lastSrc); // copy remaining over
327 return *this;
328}
329
330}; // namespace android
331
332#endif // _LIBS_UTILS_LIST_H
diff --git a/include/utils/Log.h b/include/utils/Log.h
deleted file mode 100644
index 5276a498d..000000000
--- a/include/utils/Log.h
+++ /dev/null
@@ -1,72 +0,0 @@
1/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//
18// C/C++ logging functions. See the logging documentation for API details.
19//
20// We'd like these to be available from C code (in case we import some from
21// somewhere), so this has a C interface.
22//
23// The output will be correct when the log file is shared between multiple
24// threads and/or multiple processes so long as the operating system
25// supports O_APPEND. These calls have mutex-protected data structures
26// and so are NOT reentrant. Do not use LOG in a signal handler.
27//
28#ifndef _LIBS_UTILS_LOG_H
29#define _LIBS_UTILS_LOG_H
30
31#include <sys/types.h>
32
33#include <log/log.h>
34
35#ifdef __cplusplus
36
37namespace android {
38
39/*
40 * A very simple utility that yells in the log when an operation takes too long.
41 */
42class LogIfSlow {
43public:
44 LogIfSlow(const char* tag, android_LogPriority priority,
45 int timeoutMillis, const char* message);
46 ~LogIfSlow();
47
48private:
49 const char* const mTag;
50 const android_LogPriority mPriority;
51 const int mTimeoutMillis;
52 const char* const mMessage;
53 const int64_t mStart;
54};
55
56/*
57 * Writes the specified debug log message if this block takes longer than the
58 * specified number of milliseconds to run. Includes the time actually taken.
59 *
60 * {
61 * ALOGD_IF_SLOW(50, "Excessive delay doing something.");
62 * doSomething();
63 * }
64 */
65#define ALOGD_IF_SLOW(timeoutMillis, message) \
66 android::LogIfSlow _logIfSlow(LOG_TAG, ANDROID_LOG_DEBUG, timeoutMillis, message);
67
68} // namespace android
69
70#endif // __cplusplus
71
72#endif // _LIBS_UTILS_LOG_H
diff --git a/include/utils/Looper.h b/include/utils/Looper.h
deleted file mode 100644
index a62e67f5f..000000000
--- a/include/utils/Looper.h
+++ /dev/null
@@ -1,487 +0,0 @@
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef UTILS_LOOPER_H
18#define UTILS_LOOPER_H
19
20#include <utils/threads.h>
21#include <utils/RefBase.h>
22#include <utils/KeyedVector.h>
23#include <utils/Timers.h>
24
25#include <sys/epoll.h>
26
27namespace android {
28
29/*
30 * NOTE: Since Looper is used to implement the NDK ALooper, the Looper
31 * enums and the signature of Looper_callbackFunc need to align with
32 * that implementation.
33 */
34
35/**
36 * For callback-based event loops, this is the prototype of the function
37 * that is called when a file descriptor event occurs.
38 * It is given the file descriptor it is associated with,
39 * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
40 * and the data pointer that was originally supplied.
41 *
42 * Implementations should return 1 to continue receiving callbacks, or 0
43 * to have this file descriptor and callback unregistered from the looper.
44 */
45typedef int (*Looper_callbackFunc)(int fd, int events, void* data);
46
47/**
48 * A message that can be posted to a Looper.
49 */
50struct Message {
51 Message() : what(0) { }
52 Message(int w) : what(w) { }
53
54 /* The message type. (interpretation is left up to the handler) */
55 int what;
56};
57
58
59/**
60 * Interface for a Looper message handler.
61 *
62 * The Looper holds a strong reference to the message handler whenever it has
63 * a message to deliver to it. Make sure to call Looper::removeMessages
64 * to remove any pending messages destined for the handler so that the handler
65 * can be destroyed.
66 */
67class MessageHandler : public virtual RefBase {
68protected:
69 virtual ~MessageHandler();
70
71public:
72 /**
73 * Handles a message.
74 */
75 virtual void handleMessage(const Message& message) = 0;
76};
77
78
79/**
80 * A simple proxy that holds a weak reference to a message handler.
81 */
82class WeakMessageHandler : public MessageHandler {
83protected:
84 virtual ~WeakMessageHandler();
85
86public:
87 WeakMessageHandler(const wp<MessageHandler>& handler);
88 virtual void handleMessage(const Message& message);
89
90private:
91 wp<MessageHandler> mHandler;
92};
93
94
95/**
96 * A looper callback.
97 */
98class LooperCallback : public virtual RefBase {
99protected:
100 virtual ~LooperCallback();
101
102public:
103 /**
104 * Handles a poll event for the given file descriptor.
105 * It is given the file descriptor it is associated with,
106 * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
107 * and the data pointer that was originally supplied.
108 *
109 * Implementations should return 1 to continue receiving callbacks, or 0
110 * to have this file descriptor and callback unregistered from the looper.
111 */
112 virtual int handleEvent(int fd, int events, void* data) = 0;
113};
114
115/**
116 * Wraps a Looper_callbackFunc function pointer.
117 */
118class SimpleLooperCallback : public LooperCallback {
119protected:
120 virtual ~SimpleLooperCallback();
121
122public:
123 SimpleLooperCallback(Looper_callbackFunc callback);
124 virtual int handleEvent(int fd, int events, void* data);
125
126private:
127 Looper_callbackFunc mCallback;
128};
129
130/**
131 * A polling loop that supports monitoring file descriptor events, optionally
132 * using callbacks. The implementation uses epoll() internally.
133 *
134 * A looper can be associated with a thread although there is no requirement that it must be.
135 */
136class Looper : public RefBase {
137protected:
138 virtual ~Looper();
139
140public:
141 enum {
142 /**
143 * Result from Looper_pollOnce() and Looper_pollAll():
144 * The poll was awoken using wake() before the timeout expired
145 * and no callbacks were executed and no other file descriptors were ready.
146 */
147 POLL_WAKE = -1,
148
149 /**
150 * Result from Looper_pollOnce() and Looper_pollAll():
151 * One or more callbacks were executed.
152 */
153 POLL_CALLBACK = -2,
154
155 /**
156 * Result from Looper_pollOnce() and Looper_pollAll():
157 * The timeout expired.
158 */
159 POLL_TIMEOUT = -3,
160
161 /**
162 * Result from Looper_pollOnce() and Looper_pollAll():
163 * An error occurred.
164 */
165 POLL_ERROR = -4,
166 };
167
168 /**
169 * Flags for file descriptor events that a looper can monitor.
170 *
171 * These flag bits can be combined to monitor multiple events at once.
172 */
173 enum {
174 /**
175 * The file descriptor is available for read operations.
176 */
177 EVENT_INPUT = 1 << 0,
178
179 /**
180 * The file descriptor is available for write operations.
181 */
182 EVENT_OUTPUT = 1 << 1,
183
184 /**
185 * The file descriptor has encountered an error condition.
186 *
187 * The looper always sends notifications about errors; it is not necessary
188 * to specify this event flag in the requested event set.
189 */
190 EVENT_ERROR = 1 << 2,
191
192 /**
193 * The file descriptor was hung up.
194 * For example, indicates that the remote end of a pipe or socket was closed.
195 *
196 * The looper always sends notifications about hangups; it is not necessary
197 * to specify this event flag in the requested event set.
198 */
199 EVENT_HANGUP = 1 << 3,
200
201 /**
202 * The file descriptor is invalid.
203 * For example, the file descriptor was closed prematurely.
204 *
205 * The looper always sends notifications about invalid file descriptors; it is not necessary
206 * to specify this event flag in the requested event set.
207 */
208 EVENT_INVALID = 1 << 4,
209 };
210
211 enum {
212 /**
213 * Option for Looper_prepare: this looper will accept calls to
214 * Looper_addFd() that do not have a callback (that is provide NULL
215 * for the callback). In this case the caller of Looper_pollOnce()
216 * or Looper_pollAll() MUST check the return from these functions to
217 * discover when data is available on such fds and process it.
218 */
219 PREPARE_ALLOW_NON_CALLBACKS = 1<<0
220 };
221
222 /**
223 * Creates a looper.
224 *
225 * If allowNonCallbaks is true, the looper will allow file descriptors to be
226 * registered without associated callbacks. This assumes that the caller of
227 * pollOnce() is prepared to handle callback-less events itself.
228 */
229 Looper(bool allowNonCallbacks);
230
231 /**
232 * Returns whether this looper instance allows the registration of file descriptors
233 * using identifiers instead of callbacks.
234 */
235 bool getAllowNonCallbacks() const;
236
237 /**
238 * Waits for events to be available, with optional timeout in milliseconds.
239 * Invokes callbacks for all file descriptors on which an event occurred.
240 *
241 * If the timeout is zero, returns immediately without blocking.
242 * If the timeout is negative, waits indefinitely until an event appears.
243 *
244 * Returns POLL_WAKE if the poll was awoken using wake() before
245 * the timeout expired and no callbacks were invoked and no other file
246 * descriptors were ready.
247 *
248 * Returns POLL_CALLBACK if one or more callbacks were invoked.
249 *
250 * Returns POLL_TIMEOUT if there was no data before the given
251 * timeout expired.
252 *
253 * Returns POLL_ERROR if an error occurred.
254 *
255 * Returns a value >= 0 containing an identifier if its file descriptor has data
256 * and it has no callback function (requiring the caller here to handle it).
257 * In this (and only this) case outFd, outEvents and outData will contain the poll
258 * events and data associated with the fd, otherwise they will be set to NULL.
259 *
260 * This method does not return until it has finished invoking the appropriate callbacks
261 * for all file descriptors that were signalled.
262 */
263 int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
264 inline int pollOnce(int timeoutMillis) {
265 return pollOnce(timeoutMillis, NULL, NULL, NULL);
266 }
267
268 /**
269 * Like pollOnce(), but performs all pending callbacks until all
270 * data has been consumed or a file descriptor is available with no callback.
271 * This function will never return POLL_CALLBACK.
272 */
273 int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
274 inline int pollAll(int timeoutMillis) {
275 return pollAll(timeoutMillis, NULL, NULL, NULL);
276 }
277
278 /**
279 * Wakes the poll asynchronously.
280 *
281 * This method can be called on any thread.
282 * This method returns immediately.
283 */
284 void wake();
285
286 /**
287 * Adds a new file descriptor to be polled by the looper.
288 * If the same file descriptor was previously added, it is replaced.
289 *
290 * "fd" is the file descriptor to be added.
291 * "ident" is an identifier for this event, which is returned from pollOnce().
292 * The identifier must be >= 0, or POLL_CALLBACK if providing a non-NULL callback.
293 * "events" are the poll events to wake up on. Typically this is EVENT_INPUT.
294 * "callback" is the function to call when there is an event on the file descriptor.
295 * "data" is a private data pointer to supply to the callback.
296 *
297 * There are two main uses of this function:
298 *
299 * (1) If "callback" is non-NULL, then this function will be called when there is
300 * data on the file descriptor. It should execute any events it has pending,
301 * appropriately reading from the file descriptor. The 'ident' is ignored in this case.
302 *
303 * (2) If "callback" is NULL, the 'ident' will be returned by Looper_pollOnce
304 * when its file descriptor has data available, requiring the caller to take
305 * care of processing it.
306 *
307 * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
308 *
309 * This method can be called on any thread.
310 * This method may block briefly if it needs to wake the poll.
311 *
312 * The callback may either be specified as a bare function pointer or as a smart
313 * pointer callback object. The smart pointer should be preferred because it is
314 * easier to avoid races when the callback is removed from a different thread.
315 * See removeFd() for details.
316 */
317 int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
318 int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
319
320 /**
321 * Removes a previously added file descriptor from the looper.
322 *
323 * When this method returns, it is safe to close the file descriptor since the looper
324 * will no longer have a reference to it. However, it is possible for the callback to
325 * already be running or for it to run one last time if the file descriptor was already
326 * signalled. Calling code is responsible for ensuring that this case is safely handled.
327 * For example, if the callback takes care of removing itself during its own execution either
328 * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
329 * again at any later time unless registered anew.
330 *
331 * A simple way to avoid this problem is to use the version of addFd() that takes
332 * a sp<LooperCallback> instead of a bare function pointer. The LooperCallback will
333 * be released at the appropriate time by the Looper.
334 *
335 * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
336 *
337 * This method can be called on any thread.
338 * This method may block briefly if it needs to wake the poll.
339 */
340 int removeFd(int fd);
341
342 /**
343 * Enqueues a message to be processed by the specified handler.
344 *
345 * The handler must not be null.
346 * This method can be called on any thread.
347 */
348 void sendMessage(const sp<MessageHandler>& handler, const Message& message);
349
350 /**
351 * Enqueues a message to be processed by the specified handler after all pending messages
352 * after the specified delay.
353 *
354 * The time delay is specified in uptime nanoseconds.
355 * The handler must not be null.
356 * This method can be called on any thread.
357 */
358 void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
359 const Message& message);
360
361 /**
362 * Enqueues a message to be processed by the specified handler after all pending messages
363 * at the specified time.
364 *
365 * The time is specified in uptime nanoseconds.
366 * The handler must not be null.
367 * This method can be called on any thread.
368 */
369 void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
370 const Message& message);
371
372 /**
373 * Removes all messages for the specified handler from the queue.
374 *
375 * The handler must not be null.
376 * This method can be called on any thread.
377 */
378 void removeMessages(const sp<MessageHandler>& handler);
379
380 /**
381 * Removes all messages of a particular type for the specified handler from the queue.
382 *
383 * The handler must not be null.
384 * This method can be called on any thread.
385 */
386 void removeMessages(const sp<MessageHandler>& handler, int what);
387
388 /**
389 * Returns whether this looper's thread is currently polling for more work to do.
390 * This is a good signal that the loop is still alive rather than being stuck
391 * handling a callback. Note that this method is intrinsically racy, since the
392 * state of the loop can change before you get the result back.
393 */
394 bool isPolling() const;
395
396 /**
397 * Prepares a looper associated with the calling thread, and returns it.
398 * If the thread already has a looper, it is returned. Otherwise, a new
399 * one is created, associated with the thread, and returned.
400 *
401 * The opts may be PREPARE_ALLOW_NON_CALLBACKS or 0.
402 */
403 static sp<Looper> prepare(int opts);
404
405 /**
406 * Sets the given looper to be associated with the calling thread.
407 * If another looper is already associated with the thread, it is replaced.
408 *
409 * If "looper" is NULL, removes the currently associated looper.
410 */
411 static void setForThread(const sp<Looper>& looper);
412
413 /**
414 * Returns the looper associated with the calling thread, or NULL if
415 * there is not one.
416 */
417 static sp<Looper> getForThread();
418
419private:
420 struct Request {
421 int fd;
422 int ident;
423 int events;
424 int seq;
425 sp<LooperCallback> callback;
426 void* data;
427
428 void initEventItem(struct epoll_event* eventItem) const;
429 };
430
431 struct Response {
432 int events;
433 Request request;
434 };
435
436 struct MessageEnvelope {
437 MessageEnvelope() : uptime(0) { }
438
439 MessageEnvelope(nsecs_t u, const sp<MessageHandler> h,
440 const Message& m) : uptime(u), handler(h), message(m) {
441 }
442
443 nsecs_t uptime;
444 sp<MessageHandler> handler;
445 Message message;
446 };
447
448 const bool mAllowNonCallbacks; // immutable
449
450 int mWakeEventFd; // immutable
451 Mutex mLock;
452
453 Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
454 bool mSendingMessage; // guarded by mLock
455
456 // Whether we are currently waiting for work. Not protected by a lock,
457 // any use of it is racy anyway.
458 volatile bool mPolling;
459
460 int mEpollFd; // guarded by mLock but only modified on the looper thread
461 bool mEpollRebuildRequired; // guarded by mLock
462
463 // Locked list of file descriptor monitoring requests.
464 KeyedVector<int, Request> mRequests; // guarded by mLock
465 int mNextRequestSeq;
466
467 // This state is only used privately by pollOnce and does not require a lock since
468 // it runs on a single thread.
469 Vector<Response> mResponses;
470 size_t mResponseIndex;
471 nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
472
473 int pollInner(int timeoutMillis);
474 int removeFd(int fd, int seq);
475 void awoken();
476 void pushResponse(int events, const Request& request);
477 void rebuildEpollLocked();
478 void scheduleEpollRebuildLocked();
479
480 static void initTLSKey();
481 static void threadDestructor(void *st);
482 static void initEpollEvent(struct epoll_event* eventItem);
483};
484
485} // namespace android
486
487#endif // UTILS_LOOPER_H
diff --git a/include/utils/LruCache.h b/include/utils/LruCache.h
deleted file mode 100644
index 89dccd613..000000000
--- a/include/utils/LruCache.h
+++ /dev/null
@@ -1,298 +0,0 @@
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_UTILS_LRU_CACHE_H
18#define ANDROID_UTILS_LRU_CACHE_H
19
20#include <memory>
21#include <unordered_set>
22
23#include "utils/TypeHelpers.h" // hash_t
24
25namespace android {
26
27/**
28 * GenerationCache callback used when an item is removed
29 */
30template<typename EntryKey, typename EntryValue>
31class OnEntryRemoved {
32public: