1 /*
2  * Copyright (C) 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 
17 #include "barrier.h"
18 #include "monitor.h"
19 
20 #include <string>
21 
22 #include "atomic.h"
23 #include "base/time_utils.h"
24 #include "class_linker-inl.h"
25 #include "common_runtime_test.h"
26 #include "handle_scope-inl.h"
27 #include "mirror/class-inl.h"
28 #include "mirror/string-inl.h"  // Strings are easiest to allocate
29 #include "scoped_thread_state_change.h"
30 #include "thread_pool.h"
31 
32 namespace art {
33 
34 class MonitorTest : public CommonRuntimeTest {
35  protected:
SetUpRuntimeOptions(RuntimeOptions * options)36   void SetUpRuntimeOptions(RuntimeOptions *options) OVERRIDE {
37     // Use a smaller heap
38     for (std::pair<std::string, const void*>& pair : *options) {
39       if (pair.first.find("-Xmx") == 0) {
40         pair.first = "-Xmx4M";  // Smallest we can go.
41       }
42     }
43     options->push_back(std::make_pair("-Xint", nullptr));
44   }
45  public:
46   std::unique_ptr<Monitor> monitor_;
47   Handle<mirror::String> object_;
48   Handle<mirror::String> second_object_;
49   Handle<mirror::String> watchdog_object_;
50   // One exception test is for waiting on another Thread's lock. This is used to race-free &
51   // loop-free pass
52   Thread* thread_;
53   std::unique_ptr<Barrier> barrier_;
54   std::unique_ptr<Barrier> complete_barrier_;
55   bool completed_;
56 };
57 
58 // Fill the heap.
59 static const size_t kMaxHandles = 1000000;  // Use arbitrary large amount for now.
FillHeap(Thread * self,ClassLinker * class_linker,std::unique_ptr<StackHandleScope<kMaxHandles>> * hsp,std::vector<MutableHandle<mirror::Object>> * handles)60 static void FillHeap(Thread* self, ClassLinker* class_linker,
61                      std::unique_ptr<StackHandleScope<kMaxHandles>>* hsp,
62                      std::vector<MutableHandle<mirror::Object>>* handles)
63     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
64   Runtime::Current()->GetHeap()->SetIdealFootprint(1 * GB);
65 
66   hsp->reset(new StackHandleScope<kMaxHandles>(self));
67   // Class java.lang.Object.
68   Handle<mirror::Class> c((*hsp)->NewHandle(class_linker->FindSystemClass(self,
69                                                                        "Ljava/lang/Object;")));
70   // Array helps to fill memory faster.
71   Handle<mirror::Class> ca((*hsp)->NewHandle(class_linker->FindSystemClass(self,
72                                                                         "[Ljava/lang/Object;")));
73 
74   // Start allocating with 128K
75   size_t length = 128 * KB / 4;
76   while (length > 10) {
77     MutableHandle<mirror::Object> h((*hsp)->NewHandle<mirror::Object>(
78         mirror::ObjectArray<mirror::Object>::Alloc(self, ca.Get(), length / 4)));
79     if (self->IsExceptionPending() || h.Get() == nullptr) {
80       self->ClearException();
81 
82       // Try a smaller length
83       length = length / 8;
84       // Use at most half the reported free space.
85       size_t mem = Runtime::Current()->GetHeap()->GetFreeMemory();
86       if (length * 8 > mem) {
87         length = mem / 8;
88       }
89     } else {
90       handles->push_back(h);
91     }
92   }
93 
94   // Allocate simple objects till it fails.
95   while (!self->IsExceptionPending()) {
96     MutableHandle<mirror::Object> h = (*hsp)->NewHandle<mirror::Object>(c->AllocObject(self));
97     if (!self->IsExceptionPending() && h.Get() != nullptr) {
98       handles->push_back(h);
99     }
100   }
101   self->ClearException();
102 }
103 
104 // Check that an exception can be thrown correctly.
105 // This test is potentially racy, but the timeout is long enough that it should work.
106 
107 class CreateTask : public Task {
108  public:
CreateTask(MonitorTest * monitor_test,uint64_t initial_sleep,int64_t millis,bool expected)109   explicit CreateTask(MonitorTest* monitor_test, uint64_t initial_sleep, int64_t millis,
110                       bool expected) :
111       monitor_test_(monitor_test), initial_sleep_(initial_sleep), millis_(millis),
112       expected_(expected) {}
113 
Run(Thread * self)114   void Run(Thread* self) {
115     {
116       ScopedObjectAccess soa(self);
117 
118       monitor_test_->thread_ = self;        // Pass the Thread.
119       monitor_test_->object_.Get()->MonitorEnter(self);  // Lock the object. This should transition
120       LockWord lock_after = monitor_test_->object_.Get()->GetLockWord(false);  // it to thinLocked.
121       LockWord::LockState new_state = lock_after.GetState();
122 
123       // Cannot use ASSERT only, as analysis thinks we'll keep holding the mutex.
124       if (LockWord::LockState::kThinLocked != new_state) {
125         monitor_test_->object_.Get()->MonitorExit(self);         // To appease analysis.
126         ASSERT_EQ(LockWord::LockState::kThinLocked, new_state);  // To fail the test.
127         return;
128       }
129 
130       // Force a fat lock by running identity hashcode to fill up lock word.
131       monitor_test_->object_.Get()->IdentityHashCode();
132       LockWord lock_after2 = monitor_test_->object_.Get()->GetLockWord(false);
133       LockWord::LockState new_state2 = lock_after2.GetState();
134 
135       // Cannot use ASSERT only, as analysis thinks we'll keep holding the mutex.
136       if (LockWord::LockState::kFatLocked != new_state2) {
137         monitor_test_->object_.Get()->MonitorExit(self);         // To appease analysis.
138         ASSERT_EQ(LockWord::LockState::kFatLocked, new_state2);  // To fail the test.
139         return;
140       }
141     }  // Need to drop the mutator lock to use the barrier.
142 
143     monitor_test_->barrier_->Wait(self);           // Let the other thread know we're done.
144 
145     {
146       ScopedObjectAccess soa(self);
147 
148       // Give the other task a chance to do its thing.
149       NanoSleep(initial_sleep_ * 1000 * 1000);
150 
151       // Now try to Wait on the Monitor.
152       Monitor::Wait(self, monitor_test_->object_.Get(), millis_, 0, true,
153                     ThreadState::kTimedWaiting);
154 
155       // Check the exception status against what we expect.
156       EXPECT_EQ(expected_, self->IsExceptionPending());
157       if (expected_) {
158         self->ClearException();
159       }
160     }
161 
162     monitor_test_->complete_barrier_->Wait(self);  // Wait for test completion.
163 
164     {
165       ScopedObjectAccess soa(self);
166       monitor_test_->object_.Get()->MonitorExit(self);  // Release the object. Appeases analysis.
167     }
168   }
169 
Finalize()170   void Finalize() {
171     delete this;
172   }
173 
174  private:
175   MonitorTest* monitor_test_;
176   uint64_t initial_sleep_;
177   int64_t millis_;
178   bool expected_;
179 };
180 
181 
182 class UseTask : public Task {
183  public:
UseTask(MonitorTest * monitor_test,uint64_t initial_sleep,int64_t millis,bool expected)184   UseTask(MonitorTest* monitor_test, uint64_t initial_sleep, int64_t millis, bool expected) :
185       monitor_test_(monitor_test), initial_sleep_(initial_sleep), millis_(millis),
186       expected_(expected) {}
187 
Run(Thread * self)188   void Run(Thread* self) {
189     monitor_test_->barrier_->Wait(self);  // Wait for the other thread to set up the monitor.
190 
191     {
192       ScopedObjectAccess soa(self);
193 
194       // Give the other task a chance to do its thing.
195       NanoSleep(initial_sleep_ * 1000 * 1000);
196 
197       Monitor::Wait(self, monitor_test_->object_.Get(), millis_, 0, true,
198                     ThreadState::kTimedWaiting);
199 
200       // Check the exception status against what we expect.
201       EXPECT_EQ(expected_, self->IsExceptionPending());
202       if (expected_) {
203         self->ClearException();
204       }
205     }
206 
207     monitor_test_->complete_barrier_->Wait(self);  // Wait for test completion.
208   }
209 
Finalize()210   void Finalize() {
211     delete this;
212   }
213 
214  private:
215   MonitorTest* monitor_test_;
216   uint64_t initial_sleep_;
217   int64_t millis_;
218   bool expected_;
219 };
220 
221 class InterruptTask : public Task {
222  public:
InterruptTask(MonitorTest * monitor_test,uint64_t initial_sleep,uint64_t millis)223   InterruptTask(MonitorTest* monitor_test, uint64_t initial_sleep, uint64_t millis) :
224       monitor_test_(monitor_test), initial_sleep_(initial_sleep), millis_(millis) {}
225 
Run(Thread * self)226   void Run(Thread* self) {
227     monitor_test_->barrier_->Wait(self);  // Wait for the other thread to set up the monitor.
228 
229     {
230       ScopedObjectAccess soa(self);
231 
232       // Give the other task a chance to do its thing.
233       NanoSleep(initial_sleep_ * 1000 * 1000);
234 
235       // Interrupt the other thread.
236       monitor_test_->thread_->Interrupt(self);
237 
238       // Give it some more time to get to the exception code.
239       NanoSleep(millis_ * 1000 * 1000);
240 
241       // Now try to Wait.
242       Monitor::Wait(self, monitor_test_->object_.Get(), 10, 0, true,
243                     ThreadState::kTimedWaiting);
244 
245       // No check here, as depending on scheduling we may or may not fail.
246       if (self->IsExceptionPending()) {
247         self->ClearException();
248       }
249     }
250 
251     monitor_test_->complete_barrier_->Wait(self);  // Wait for test completion.
252   }
253 
Finalize()254   void Finalize() {
255     delete this;
256   }
257 
258  private:
259   MonitorTest* monitor_test_;
260   uint64_t initial_sleep_;
261   uint64_t millis_;
262 };
263 
264 class WatchdogTask : public Task {
265  public:
WatchdogTask(MonitorTest * monitor_test)266   explicit WatchdogTask(MonitorTest* monitor_test) : monitor_test_(monitor_test) {}
267 
Run(Thread * self)268   void Run(Thread* self) {
269     ScopedObjectAccess soa(self);
270 
271     monitor_test_->watchdog_object_.Get()->MonitorEnter(self);        // Lock the object.
272 
273     monitor_test_->watchdog_object_.Get()->Wait(self, 30 * 1000, 0);  // Wait for 30s, or being
274                                                                       // woken up.
275 
276     monitor_test_->watchdog_object_.Get()->MonitorExit(self);         // Release the lock.
277 
278     if (!monitor_test_->completed_) {
279       LOG(FATAL) << "Watchdog timeout!";
280     }
281   }
282 
Finalize()283   void Finalize() {
284     delete this;
285   }
286 
287  private:
288   MonitorTest* monitor_test_;
289 };
290 
CommonWaitSetup(MonitorTest * test,ClassLinker * class_linker,uint64_t create_sleep,int64_t c_millis,bool c_expected,bool interrupt,uint64_t use_sleep,int64_t u_millis,bool u_expected,const char * pool_name)291 static void CommonWaitSetup(MonitorTest* test, ClassLinker* class_linker, uint64_t create_sleep,
292                             int64_t c_millis, bool c_expected, bool interrupt, uint64_t use_sleep,
293                             int64_t u_millis, bool u_expected, const char* pool_name) {
294   // First create the object we lock. String is easiest.
295   StackHandleScope<3> hs(Thread::Current());
296   {
297     ScopedObjectAccess soa(Thread::Current());
298     test->object_ = hs.NewHandle(mirror::String::AllocFromModifiedUtf8(Thread::Current(),
299                                                                        "hello, world!"));
300     test->watchdog_object_ = hs.NewHandle(mirror::String::AllocFromModifiedUtf8(Thread::Current(),
301                                                                                 "hello, world!"));
302   }
303 
304   // Create the barrier used to synchronize.
305   test->barrier_ = std::unique_ptr<Barrier>(new Barrier(2));
306   test->complete_barrier_ = std::unique_ptr<Barrier>(new Barrier(3));
307   test->completed_ = false;
308 
309   // Fill the heap.
310   std::unique_ptr<StackHandleScope<kMaxHandles>> hsp;
311   std::vector<MutableHandle<mirror::Object>> handles;
312   {
313     Thread* self = Thread::Current();
314     ScopedObjectAccess soa(self);
315 
316     // Our job: Fill the heap, then try Wait.
317     FillHeap(self, class_linker, &hsp, &handles);
318 
319     // Now release everything.
320     auto it = handles.begin();
321     auto end = handles.end();
322 
323     for ( ; it != end; ++it) {
324       it->Assign(nullptr);
325     }
326   }  // Need to drop the mutator lock to allow barriers.
327 
328   Thread* self = Thread::Current();
329   ThreadPool thread_pool(pool_name, 3);
330   thread_pool.AddTask(self, new CreateTask(test, create_sleep, c_millis, c_expected));
331   if (interrupt) {
332     thread_pool.AddTask(self, new InterruptTask(test, use_sleep, static_cast<uint64_t>(u_millis)));
333   } else {
334     thread_pool.AddTask(self, new UseTask(test, use_sleep, u_millis, u_expected));
335   }
336   thread_pool.AddTask(self, new WatchdogTask(test));
337   thread_pool.StartWorkers(self);
338 
339   // Wait on completion barrier.
340   test->complete_barrier_->Wait(Thread::Current());
341   test->completed_ = true;
342 
343   // Wake the watchdog.
344   {
345     ScopedObjectAccess soa(Thread::Current());
346 
347     test->watchdog_object_.Get()->MonitorEnter(self);     // Lock the object.
348     test->watchdog_object_.Get()->NotifyAll(self);        // Wake up waiting parties.
349     test->watchdog_object_.Get()->MonitorExit(self);      // Release the lock.
350   }
351 
352   thread_pool.StopWorkers(self);
353 }
354 
355 
356 // First test: throwing an exception when trying to wait in Monitor with another thread.
TEST_F(MonitorTest,CheckExceptionsWait1)357 TEST_F(MonitorTest, CheckExceptionsWait1) {
358   // Make the CreateTask wait 10ms, the UseTask wait 10ms.
359   // => The use task will get the lock first and get to self == owner check.
360   // This will lead to OOM and monitor error messages in the log.
361   ScopedLogSeverity sls(LogSeverity::FATAL);
362   CommonWaitSetup(this, class_linker_, 10, 50, false, false, 2, 50, true,
363                   "Monitor test thread pool 1");
364 }
365 
366 // Second test: throwing an exception for invalid wait time.
TEST_F(MonitorTest,CheckExceptionsWait2)367 TEST_F(MonitorTest, CheckExceptionsWait2) {
368   // Make the CreateTask wait 0ms, the UseTask wait 10ms.
369   // => The create task will get the lock first and get to ms >= 0
370   // This will lead to OOM and monitor error messages in the log.
371   ScopedLogSeverity sls(LogSeverity::FATAL);
372   CommonWaitSetup(this, class_linker_, 0, -1, true, false, 10, 50, true,
373                   "Monitor test thread pool 2");
374 }
375 
376 // Third test: throwing an interrupted-exception.
TEST_F(MonitorTest,CheckExceptionsWait3)377 TEST_F(MonitorTest, CheckExceptionsWait3) {
378   // Make the CreateTask wait 0ms, then Wait for a long time. Make the InterruptTask wait 10ms,
379   // after which it will interrupt the create task and then wait another 10ms.
380   // => The create task will get to the interrupted-exception throw.
381   // This will lead to OOM and monitor error messages in the log.
382   ScopedLogSeverity sls(LogSeverity::FATAL);
383   CommonWaitSetup(this, class_linker_, 0, 500, true, true, 10, 50, true,
384                   "Monitor test thread pool 3");
385 }
386 
387 }  // namespace art
388