1 /*
2  * Copyright (C) 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 #include <general_test/heap_exhaustion_stability_test.h>
18 
19 #include <cinttypes>
20 #include <cstddef>
21 
22 #include <shared/send_message.h>
23 #include <shared/time_util.h>
24 
25 #include <chre.h>
26 
27 using nanoapp_testing::kOneMillisecondInNanoseconds;
28 using nanoapp_testing::kOneSecondInNanoseconds;
29 using nanoapp_testing::sendFailureToHost;
30 using nanoapp_testing::sendFatalFailureToHost;
31 using nanoapp_testing::sendSuccessToHost;
32 
33 /*
34  * We set an "exhaustion timer" to go off when we're ready for the test to
35  * be over.  Then we exhaust the heap.
36  *
37  * We try a series of chre*() calls with the heap exhausted.  For many of
38  * these calls, we're less interested in them succeeding than in the system
39  * just not crashing.  However, for things which claim success, we require
40  * they succeed.
41  *
42  * To track the things which claim success, we have two "stages", kTimerStage
43  * and kEventStage.
44  *
45  * When the "exhaustion timer" fires, we free our memory, and make sure our
46  * stages have all succeeded.
47  */
48 
49 namespace general_test {
50 
51 // Note: We use pointers to the 'duration' to serve as our timer event data.
52 // Thus we make this "static const" instead of "constexpr", as we expect
53 // them to have backing memory.
54 
55 static const uint64_t kExhaustionDuration = 5 * kOneSecondInNanoseconds;
56 static const uint64_t kShortDuration = 10 * kOneMillisecondInNanoseconds;
57 
58 constexpr uint16_t kEventType = CHRE_EVENT_FIRST_USER_VALUE;
59 
60 constexpr uint32_t kTimerStage = 0;
61 constexpr uint32_t kEventStage = 1;
62 
exhaustHeap()63 void HeapExhaustionStabilityTest::exhaustHeap() {
64   constexpr size_t kNumPtrs = 256;
65   mExhaustionPtrs = reinterpret_cast<void **>(
66       chreHeapAlloc(kNumPtrs * sizeof(*mExhaustionPtrs)));
67   if (mExhaustionPtrs == nullptr) {
68     // Oh, the irony.
69     sendFatalFailureToHost("Insufficient free heap to exhaust the heap.");
70   }
71 
72   // We start by trying to allocate massive sizes (256MB to start).
73   // When we're not able to allocate massive sizes, we cut the size in
74   // half.  We repeat until we've either done kNumPtrs allocations,
75   // or reduced our allocation size below 16 bytes.
76   uint32_t allocSize = 1024 * 1024 * 256;
77   for (mExhaustionPtrCount = 0; mExhaustionPtrCount < kNumPtrs;
78        mExhaustionPtrCount++) {
79     void *ptr = chreHeapAlloc(allocSize);
80     while (ptr == nullptr) {
81       allocSize /= 2;
82       if (allocSize < 4) {
83         break;
84       }
85       ptr = chreHeapAlloc(allocSize);
86     }
87     if (ptr == nullptr) {
88       break;
89     }
90     mExhaustionPtrs[mExhaustionPtrCount] = ptr;
91   }
92   if (mExhaustionPtrCount == 0) {
93     sendFatalFailureToHost("Failed to allocate anything for heap exhaustion");
94   }
95 }
96 
freeMemory()97 void HeapExhaustionStabilityTest::freeMemory() {
98   for (size_t i = 0; i < mExhaustionPtrCount; i++) {
99     chreHeapFree(mExhaustionPtrs[i]);
100   }
101   chreHeapFree(mExhaustionPtrs);
102 }
103 
HeapExhaustionStabilityTest()104 HeapExhaustionStabilityTest::HeapExhaustionStabilityTest()
105     : Test(CHRE_API_VERSION_1_0) {}
106 
setUp(uint32_t messageSize,const void *)107 void HeapExhaustionStabilityTest::setUp(uint32_t messageSize,
108                                         const void * /* message */) {
109   mInMethod = true;
110   if (messageSize != 0) {
111     sendFatalFailureToHost(
112         "HeapExhaustionStability message expects 0 additional bytes, got ",
113         &messageSize);
114   }
115 
116   if (chreTimerSet(kExhaustionDuration, &kExhaustionDuration, true) ==
117       CHRE_TIMER_INVALID) {
118     sendFatalFailureToHost("Unable to set initial timer");
119   }
120 
121   exhaustHeap();
122 
123   testLog(messageSize);
124   testSetTimer();
125   testSendEvent();
126   testSensor();
127   // TODO(b/32114261): This method currently doesn't test anything.
128   testMessageToHost();
129 
130   // Some of the above 'test' methods might trigger events.  Even if they
131   // don't, the kExhaustionDuration timer we set earlier should trigger
132   // eventually, and that's when we'll conclude the test.
133   mInMethod = false;
134 }
135 
testLog(uint32_t zero)136 void HeapExhaustionStabilityTest::testLog(uint32_t zero) {
137   // This doesn't need to land in the log (and indeed we have no automated
138   // means of checking that right now anyway), but it shouldn't crash.
139   chreLog(CHRE_LOG_INFO, "Test log %s, zero: %" PRId32, "message", zero);
140 }
141 
testSetTimer()142 void HeapExhaustionStabilityTest::testSetTimer() {
143   if (chreTimerSet(kShortDuration, &kShortDuration, true) !=
144       CHRE_TIMER_INVALID) {
145     // CHRE claims we were able to set this timer.  We'll
146     // mark this stage a success when the timer fires.
147   } else {
148     // CHRE was not able to set this timer.  That's okay, since we're
149     // out of heap.  We'll mark this stage as a success.
150     markSuccess(kTimerStage);
151   }
152 }
153 
testSendEvent()154 void HeapExhaustionStabilityTest::testSendEvent() {
155   if (chreSendEvent(kEventType, nullptr, nullptr, chreGetInstanceId())) {
156     // CHRE claims we were able to send this event.  We'll make
157     // this stage a success when the event is received.
158   } else {
159     // CHRE was not able to send this event.  That's okay, since we're
160     // out of heap.  We'll mark this stage as a success.
161     markSuccess(kEventStage);
162   }
163 }
164 
testSensor()165 void HeapExhaustionStabilityTest::testSensor() {
166   static constexpr uint8_t kSensorType = CHRE_SENSOR_TYPE_ACCELEROMETER;
167   uint32_t handle;
168   if (!chreSensorFindDefault(kSensorType, &handle)) {
169     // We still expect this to succeed without any heap left.
170     sendFatalFailureToHost("chreSensorFindDefault failed");
171   }
172   chreSensorInfo info;
173   if (!chreGetSensorInfo(handle, &info)) {
174     // We still expect this to succeed, since we're supplying the memory.
175     sendFatalFailureToHost("chreGetSensorInfo failed");
176   }
177   if (info.sensorType != kSensorType) {
178     sendFatalFailureToHost("Invalid sensor info provided");
179   }
180 
181   chreSensorSamplingStatus samplingStatus;
182   if (!chreGetSensorSamplingStatus(handle, &samplingStatus)) {
183     // We still expect this to succeed, since we're supplying the memory.
184     sendFatalFailureToHost("chreGetSensorSamplingStatus failed");
185   }
186 
187   // TODO: We might want to consider calling chreSensorConfigure() for a
188   //     more robust test of this.  However, we don't expect sensor events to
189   //     necessarily get delivered under heap exhaustion, so it's unclear
190   //     how we'd make sure we eventually tell the system we're DONE with
191   //     the sensor (setting a timer isn't assured to work at this point).
192 }
193 
testMessageToHost()194 void HeapExhaustionStabilityTest::testMessageToHost() {
195   // TODO(b/32114261): We should invoke sendMessageToHost() here.
196   //     Unfortunately, this is a real pain due to this bug, as we need to
197   //     duplicate much of the contents of shared/send_message.cc to
198   //     add the hack-around bytes (the method itself will internally
199   //     fail if the send attempt fails, but we're in a state where
200   //     we'll allow a failed send attempt).  Or we need to take this
201   //     off of the General test infrastructure to allow raw byte sending.
202   //     That seems not worth the effort for NYC, and just easier to wait
203   //     until OMC when this is much easier to implement.
204   // OMC Note: When we've fixed this bug, and added a send here, we'll
205   //     need to make this no longer Simple protocol, since this nanoapp
206   //     might send a message.
207 }
208 
handleEvent(uint32_t senderInstanceId,uint16_t eventType,const void * eventData)209 void HeapExhaustionStabilityTest::handleEvent(uint32_t senderInstanceId,
210                                               uint16_t eventType,
211                                               const void *eventData) {
212   if (mInMethod) {
213     sendFatalFailureToHost(
214         "handleEvent invoked while another nanoapp method is running");
215   }
216   mInMethod = true;
217 
218   if (eventType == CHRE_EVENT_TIMER) {
219     handleTimer(senderInstanceId, eventData);
220   } else if (eventType == kEventType) {
221     handleSelfEvent(senderInstanceId, eventData);
222   } else {
223     unexpectedEvent(eventType);
224   }
225   mInMethod = false;
226 }
227 
handleTimer(uint32_t senderInstanceId,const void * eventData)228 void HeapExhaustionStabilityTest::handleTimer(uint32_t senderInstanceId,
229                                               const void *eventData) {
230   if (senderInstanceId != CHRE_INSTANCE_ID) {
231     sendFatalFailureToHost("handleTimer with unexpected sender:",
232                            &senderInstanceId);
233   }
234   if (eventData == &kShortDuration) {
235     // This was the timer we triggered while the heap was exhausted.
236     markSuccess(kTimerStage);
237 
238   } else if (eventData == &kExhaustionDuration) {
239     // Our test is done.
240     freeMemory();
241     if (mFinishedBitmask != kAllFinished) {
242       sendFatalFailureToHost("Done with test, but not all stages done.",
243                              &mFinishedBitmask);
244     }
245     sendSuccessToHost();
246 
247   } else {
248     sendFatalFailureToHost("Unexpected timer eventData");
249   }
250 }
251 
handleSelfEvent(uint32_t senderInstanceId,const void * eventData)252 void HeapExhaustionStabilityTest::handleSelfEvent(uint32_t senderInstanceId,
253                                                   const void *eventData) {
254   if (senderInstanceId != chreGetInstanceId()) {
255     sendFatalFailureToHost("handleSelfEvent with unexpected sender:",
256                            &senderInstanceId);
257   }
258   if (eventData != nullptr) {
259     sendFatalFailureToHost("Unexpected data for event to self");
260   }
261   markSuccess(kEventStage);
262 }
263 
markSuccess(uint32_t stage)264 void HeapExhaustionStabilityTest::markSuccess(uint32_t stage) {
265   chreLog(CHRE_LOG_DEBUG, "Stage %" PRIu32 " succeeded", stage);
266   uint32_t finishedBit = (1 << stage);
267   if ((kAllFinished & finishedBit) == 0) {
268     sendFatalFailureToHost("markSuccess bad stage", &stage);
269   }
270   if ((mFinishedBitmask & finishedBit) != 0) {
271     // This could be when a timer/event method returned 'false', but
272     // actually did end up triggering an event.
273     sendFatalFailureToHost("markSuccess stage triggered twice", &stage);
274   }
275   mFinishedBitmask |= finishedBit;
276   // Note that unlike many markSuccess() implementations, we do not
277   // check against kAllFinished here.  That happens when the
278   // timer for kExhaustionDuration fires.
279 }
280 
281 }  // namespace general_test
282