• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "rtc_base/thread.h"
12 
13 #if defined(WEBRTC_WIN)
14 #include <comdef.h>
15 #elif defined(WEBRTC_POSIX)
16 #include <time.h>
17 #else
18 #error "Either WEBRTC_WIN or WEBRTC_POSIX needs to be defined."
19 #endif
20 
21 #if defined(WEBRTC_WIN)
22 // Disable warning that we don't care about:
23 // warning C4722: destructor never returns, potential memory leak
24 #pragma warning(disable : 4722)
25 #endif
26 
27 #include <stdio.h>
28 
29 #include <utility>
30 
31 #include "absl/algorithm/container.h"
32 #include "rtc_base/atomic_ops.h"
33 #include "rtc_base/checks.h"
34 #include "rtc_base/deprecated/recursive_critical_section.h"
35 #include "rtc_base/logging.h"
36 #include "rtc_base/null_socket_server.h"
37 #include "rtc_base/synchronization/sequence_checker.h"
38 #include "rtc_base/task_utils/to_queued_task.h"
39 #include "rtc_base/time_utils.h"
40 #include "rtc_base/trace_event.h"
41 
42 #if defined(WEBRTC_MAC)
43 #include "rtc_base/system/cocoa_threading.h"
44 
45 /*
46  * These are forward-declarations for methods that are part of the
47  * ObjC runtime. They are declared in the private header objc-internal.h.
48  * These calls are what clang inserts when using @autoreleasepool in ObjC,
49  * but here they are used directly in order to keep this file C++.
50  * https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support
51  */
52 extern "C" {
53 void* objc_autoreleasePoolPush(void);
54 void objc_autoreleasePoolPop(void* pool);
55 }
56 
57 namespace {
58 class ScopedAutoReleasePool {
59  public:
ScopedAutoReleasePool()60   ScopedAutoReleasePool() : pool_(objc_autoreleasePoolPush()) {}
~ScopedAutoReleasePool()61   ~ScopedAutoReleasePool() { objc_autoreleasePoolPop(pool_); }
62 
63  private:
64   void* const pool_;
65 };
66 }  // namespace
67 #endif
68 
69 namespace rtc {
70 namespace {
71 
72 const int kSlowDispatchLoggingThreshold = 50;  // 50 ms
73 
74 class MessageHandlerWithTask final : public MessageHandler {
75  public:
76   MessageHandlerWithTask() = default;
77 
OnMessage(Message * msg)78   void OnMessage(Message* msg) override {
79     static_cast<rtc_thread_internal::MessageLikeTask*>(msg->pdata)->Run();
80     delete msg->pdata;
81   }
82 
83  private:
~MessageHandlerWithTask()84   ~MessageHandlerWithTask() override {}
85 
86   RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
87 };
88 
89 class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
90  public:
MarkProcessingCritScope(const RecursiveCriticalSection * cs,size_t * processing)91   MarkProcessingCritScope(const RecursiveCriticalSection* cs,
92                           size_t* processing) RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
93       : cs_(cs), processing_(processing) {
94     cs_->Enter();
95     *processing_ += 1;
96   }
97 
RTC_UNLOCK_FUNCTION()98   ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
99     *processing_ -= 1;
100     cs_->Leave();
101   }
102 
103  private:
104   const RecursiveCriticalSection* const cs_;
105   size_t* processing_;
106 
107   RTC_DISALLOW_COPY_AND_ASSIGN(MarkProcessingCritScope);
108 };
109 
110 }  // namespace
111 
Instance()112 ThreadManager* ThreadManager::Instance() {
113   static ThreadManager* const thread_manager = new ThreadManager();
114   return thread_manager;
115 }
116 
~ThreadManager()117 ThreadManager::~ThreadManager() {
118   // By above RTC_DEFINE_STATIC_LOCAL.
119   RTC_NOTREACHED() << "ThreadManager should never be destructed.";
120 }
121 
122 // static
Add(Thread * message_queue)123 void ThreadManager::Add(Thread* message_queue) {
124   return Instance()->AddInternal(message_queue);
125 }
AddInternal(Thread * message_queue)126 void ThreadManager::AddInternal(Thread* message_queue) {
127   CritScope cs(&crit_);
128   // Prevent changes while the list of message queues is processed.
129   RTC_DCHECK_EQ(processing_, 0);
130   message_queues_.push_back(message_queue);
131 }
132 
133 // static
Remove(Thread * message_queue)134 void ThreadManager::Remove(Thread* message_queue) {
135   return Instance()->RemoveInternal(message_queue);
136 }
RemoveInternal(Thread * message_queue)137 void ThreadManager::RemoveInternal(Thread* message_queue) {
138   {
139     CritScope cs(&crit_);
140     // Prevent changes while the list of message queues is processed.
141     RTC_DCHECK_EQ(processing_, 0);
142     std::vector<Thread*>::iterator iter;
143     iter = absl::c_find(message_queues_, message_queue);
144     if (iter != message_queues_.end()) {
145       message_queues_.erase(iter);
146     }
147 #if RTC_DCHECK_IS_ON
148     RemoveFromSendGraph(message_queue);
149 #endif
150   }
151 }
152 
153 #if RTC_DCHECK_IS_ON
RemoveFromSendGraph(Thread * thread)154 void ThreadManager::RemoveFromSendGraph(Thread* thread) {
155   for (auto it = send_graph_.begin(); it != send_graph_.end();) {
156     if (it->first == thread) {
157       it = send_graph_.erase(it);
158     } else {
159       it->second.erase(thread);
160       ++it;
161     }
162   }
163 }
164 
RegisterSendAndCheckForCycles(Thread * source,Thread * target)165 void ThreadManager::RegisterSendAndCheckForCycles(Thread* source,
166                                                   Thread* target) {
167   CritScope cs(&crit_);
168   std::deque<Thread*> all_targets({target});
169   // We check the pre-existing who-sends-to-who graph for any path from target
170   // to source. This loop is guaranteed to terminate because per the send graph
171   // invariant, there are no cycles in the graph.
172   for (size_t i = 0; i < all_targets.size(); i++) {
173     const auto& targets = send_graph_[all_targets[i]];
174     all_targets.insert(all_targets.end(), targets.begin(), targets.end());
175   }
176   RTC_CHECK_EQ(absl::c_count(all_targets, source), 0)
177       << " send loop between " << source->name() << " and " << target->name();
178 
179   // We may now insert source -> target without creating a cycle, since there
180   // was no path from target to source per the prior CHECK.
181   send_graph_[source].insert(target);
182 }
183 #endif
184 
185 // static
Clear(MessageHandler * handler)186 void ThreadManager::Clear(MessageHandler* handler) {
187   return Instance()->ClearInternal(handler);
188 }
ClearInternal(MessageHandler * handler)189 void ThreadManager::ClearInternal(MessageHandler* handler) {
190   // Deleted objects may cause re-entrant calls to ClearInternal. This is
191   // allowed as the list of message queues does not change while queues are
192   // cleared.
193   MarkProcessingCritScope cs(&crit_, &processing_);
194   for (Thread* queue : message_queues_) {
195     queue->Clear(handler);
196   }
197 }
198 
199 // static
ProcessAllMessageQueuesForTesting()200 void ThreadManager::ProcessAllMessageQueuesForTesting() {
201   return Instance()->ProcessAllMessageQueuesInternal();
202 }
203 
ProcessAllMessageQueuesInternal()204 void ThreadManager::ProcessAllMessageQueuesInternal() {
205   // This works by posting a delayed message at the current time and waiting
206   // for it to be dispatched on all queues, which will ensure that all messages
207   // that came before it were also dispatched.
208   volatile int queues_not_done = 0;
209 
210   // This class is used so that whether the posted message is processed, or the
211   // message queue is simply cleared, queues_not_done gets decremented.
212   class ScopedIncrement : public MessageData {
213    public:
214     ScopedIncrement(volatile int* value) : value_(value) {
215       AtomicOps::Increment(value_);
216     }
217     ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
218 
219    private:
220     volatile int* value_;
221   };
222 
223   {
224     MarkProcessingCritScope cs(&crit_, &processing_);
225     for (Thread* queue : message_queues_) {
226       if (!queue->IsProcessingMessagesForTesting()) {
227         // If the queue is not processing messages, it can
228         // be ignored. If we tried to post a message to it, it would be dropped
229         // or ignored.
230         continue;
231       }
232       queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
233                          new ScopedIncrement(&queues_not_done));
234     }
235   }
236 
237   rtc::Thread* current = rtc::Thread::Current();
238   // Note: One of the message queues may have been on this thread, which is
239   // why we can't synchronously wait for queues_not_done to go to 0; we need
240   // to process messages as well.
241   while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
242     if (current) {
243       current->ProcessMessages(0);
244     }
245   }
246 }
247 
248 // static
Current()249 Thread* Thread::Current() {
250   ThreadManager* manager = ThreadManager::Instance();
251   Thread* thread = manager->CurrentThread();
252 
253 #ifndef NO_MAIN_THREAD_WRAPPING
254   // Only autowrap the thread which instantiated the ThreadManager.
255   if (!thread && manager->IsMainThread()) {
256     thread = new Thread(SocketServer::CreateDefault());
257     thread->WrapCurrentWithThreadManager(manager, true);
258   }
259 #endif
260 
261   return thread;
262 }
263 
264 #if defined(WEBRTC_POSIX)
ThreadManager()265 ThreadManager::ThreadManager() : main_thread_ref_(CurrentThreadRef()) {
266 #if defined(WEBRTC_MAC)
267   InitCocoaMultiThreading();
268 #endif
269   pthread_key_create(&key_, nullptr);
270 }
271 
CurrentThread()272 Thread* ThreadManager::CurrentThread() {
273   return static_cast<Thread*>(pthread_getspecific(key_));
274 }
275 
SetCurrentThreadInternal(Thread * thread)276 void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
277   pthread_setspecific(key_, thread);
278 }
279 #endif
280 
281 #if defined(WEBRTC_WIN)
ThreadManager()282 ThreadManager::ThreadManager()
283     : key_(TlsAlloc()), main_thread_ref_(CurrentThreadRef()) {}
284 
CurrentThread()285 Thread* ThreadManager::CurrentThread() {
286   return static_cast<Thread*>(TlsGetValue(key_));
287 }
288 
SetCurrentThreadInternal(Thread * thread)289 void ThreadManager::SetCurrentThreadInternal(Thread* thread) {
290   TlsSetValue(key_, thread);
291 }
292 #endif
293 
SetCurrentThread(Thread * thread)294 void ThreadManager::SetCurrentThread(Thread* thread) {
295 #if RTC_DLOG_IS_ON
296   if (CurrentThread() && thread) {
297     RTC_DLOG(LS_ERROR) << "SetCurrentThread: Overwriting an existing value?";
298   }
299 #endif  // RTC_DLOG_IS_ON
300 
301   if (thread) {
302     thread->EnsureIsCurrentTaskQueue();
303   } else {
304     Thread* current = CurrentThread();
305     if (current) {
306       // The current thread is being cleared, e.g. as a result of
307       // UnwrapCurrent() being called or when a thread is being stopped
308       // (see PreRun()). This signals that the Thread instance is being detached
309       // from the thread, which also means that TaskQueue::Current() must not
310       // return a pointer to the Thread instance.
311       current->ClearCurrentTaskQueue();
312     }
313   }
314 
315   SetCurrentThreadInternal(thread);
316 }
317 
ChangeCurrentThreadForTest(rtc::Thread * thread)318 void rtc::ThreadManager::ChangeCurrentThreadForTest(rtc::Thread* thread) {
319   SetCurrentThreadInternal(thread);
320 }
321 
WrapCurrentThread()322 Thread* ThreadManager::WrapCurrentThread() {
323   Thread* result = CurrentThread();
324   if (nullptr == result) {
325     result = new Thread(SocketServer::CreateDefault());
326     result->WrapCurrentWithThreadManager(this, true);
327   }
328   return result;
329 }
330 
UnwrapCurrentThread()331 void ThreadManager::UnwrapCurrentThread() {
332   Thread* t = CurrentThread();
333   if (t && !(t->IsOwned())) {
334     t->UnwrapCurrent();
335     delete t;
336   }
337 }
338 
IsMainThread()339 bool ThreadManager::IsMainThread() {
340   return IsThreadRefEqual(CurrentThreadRef(), main_thread_ref_);
341 }
342 
ScopedDisallowBlockingCalls()343 Thread::ScopedDisallowBlockingCalls::ScopedDisallowBlockingCalls()
344     : thread_(Thread::Current()),
345       previous_state_(thread_->SetAllowBlockingCalls(false)) {}
346 
~ScopedDisallowBlockingCalls()347 Thread::ScopedDisallowBlockingCalls::~ScopedDisallowBlockingCalls() {
348   RTC_DCHECK(thread_->IsCurrent());
349   thread_->SetAllowBlockingCalls(previous_state_);
350 }
351 
Thread(SocketServer * ss)352 Thread::Thread(SocketServer* ss) : Thread(ss, /*do_init=*/true) {}
353 
Thread(std::unique_ptr<SocketServer> ss)354 Thread::Thread(std::unique_ptr<SocketServer> ss)
355     : Thread(std::move(ss), /*do_init=*/true) {}
356 
Thread(SocketServer * ss,bool do_init)357 Thread::Thread(SocketServer* ss, bool do_init)
358     : fPeekKeep_(false),
359       delayed_next_num_(0),
360       fInitialized_(false),
361       fDestroyed_(false),
362       stop_(0),
363       ss_(ss) {
364   RTC_DCHECK(ss);
365   ss_->SetMessageQueue(this);
366   SetName("Thread", this);  // default name
367   if (do_init) {
368     DoInit();
369   }
370 }
371 
Thread(std::unique_ptr<SocketServer> ss,bool do_init)372 Thread::Thread(std::unique_ptr<SocketServer> ss, bool do_init)
373     : Thread(ss.get(), do_init) {
374   own_ss_ = std::move(ss);
375 }
376 
~Thread()377 Thread::~Thread() {
378   Stop();
379   DoDestroy();
380 }
381 
DoInit()382 void Thread::DoInit() {
383   if (fInitialized_) {
384     return;
385   }
386 
387   fInitialized_ = true;
388   ThreadManager::Add(this);
389 }
390 
DoDestroy()391 void Thread::DoDestroy() {
392   if (fDestroyed_) {
393     return;
394   }
395 
396   fDestroyed_ = true;
397   // The signal is done from here to ensure
398   // that it always gets called when the queue
399   // is going away.
400   SignalQueueDestroyed();
401   ThreadManager::Remove(this);
402   ClearInternal(nullptr, MQID_ANY, nullptr);
403 
404   if (ss_) {
405     ss_->SetMessageQueue(nullptr);
406   }
407 }
408 
socketserver()409 SocketServer* Thread::socketserver() {
410   return ss_;
411 }
412 
WakeUpSocketServer()413 void Thread::WakeUpSocketServer() {
414   ss_->WakeUp();
415 }
416 
Quit()417 void Thread::Quit() {
418   AtomicOps::ReleaseStore(&stop_, 1);
419   WakeUpSocketServer();
420 }
421 
IsQuitting()422 bool Thread::IsQuitting() {
423   return AtomicOps::AcquireLoad(&stop_) != 0;
424 }
425 
Restart()426 void Thread::Restart() {
427   AtomicOps::ReleaseStore(&stop_, 0);
428 }
429 
Peek(Message * pmsg,int cmsWait)430 bool Thread::Peek(Message* pmsg, int cmsWait) {
431   if (fPeekKeep_) {
432     *pmsg = msgPeek_;
433     return true;
434   }
435   if (!Get(pmsg, cmsWait))
436     return false;
437   msgPeek_ = *pmsg;
438   fPeekKeep_ = true;
439   return true;
440 }
441 
Get(Message * pmsg,int cmsWait,bool process_io)442 bool Thread::Get(Message* pmsg, int cmsWait, bool process_io) {
443   // Return and clear peek if present
444   // Always return the peek if it exists so there is Peek/Get symmetry
445 
446   if (fPeekKeep_) {
447     *pmsg = msgPeek_;
448     fPeekKeep_ = false;
449     return true;
450   }
451 
452   // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
453 
454   int64_t cmsTotal = cmsWait;
455   int64_t cmsElapsed = 0;
456   int64_t msStart = TimeMillis();
457   int64_t msCurrent = msStart;
458   while (true) {
459     // Check for posted events
460     int64_t cmsDelayNext = kForever;
461     bool first_pass = true;
462     while (true) {
463       // All queue operations need to be locked, but nothing else in this loop
464       // (specifically handling disposed message) can happen inside the crit.
465       // Otherwise, disposed MessageHandlers will cause deadlocks.
466       {
467         CritScope cs(&crit_);
468         // On the first pass, check for delayed messages that have been
469         // triggered and calculate the next trigger time.
470         if (first_pass) {
471           first_pass = false;
472           while (!delayed_messages_.empty()) {
473             if (msCurrent < delayed_messages_.top().run_time_ms_) {
474               cmsDelayNext =
475                   TimeDiff(delayed_messages_.top().run_time_ms_, msCurrent);
476               break;
477             }
478             messages_.push_back(delayed_messages_.top().msg_);
479             delayed_messages_.pop();
480           }
481         }
482         // Pull a message off the message queue, if available.
483         if (messages_.empty()) {
484           break;
485         } else {
486           *pmsg = messages_.front();
487           messages_.pop_front();
488         }
489       }  // crit_ is released here.
490 
491       // If this was a dispose message, delete it and skip it.
492       if (MQID_DISPOSE == pmsg->message_id) {
493         RTC_DCHECK(nullptr == pmsg->phandler);
494         delete pmsg->pdata;
495         *pmsg = Message();
496         continue;
497       }
498       return true;
499     }
500 
501     if (IsQuitting())
502       break;
503 
504     // Which is shorter, the delay wait or the asked wait?
505 
506     int64_t cmsNext;
507     if (cmsWait == kForever) {
508       cmsNext = cmsDelayNext;
509     } else {
510       cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
511       if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
512         cmsNext = cmsDelayNext;
513     }
514 
515     {
516       // Wait and multiplex in the meantime
517       if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
518         return false;
519     }
520 
521     // If the specified timeout expired, return
522 
523     msCurrent = TimeMillis();
524     cmsElapsed = TimeDiff(msCurrent, msStart);
525     if (cmsWait != kForever) {
526       if (cmsElapsed >= cmsWait)
527         return false;
528     }
529   }
530   return false;
531 }
532 
Post(const Location & posted_from,MessageHandler * phandler,uint32_t id,MessageData * pdata,bool time_sensitive)533 void Thread::Post(const Location& posted_from,
534                   MessageHandler* phandler,
535                   uint32_t id,
536                   MessageData* pdata,
537                   bool time_sensitive) {
538   RTC_DCHECK(!time_sensitive);
539   if (IsQuitting()) {
540     delete pdata;
541     return;
542   }
543 
544   // Keep thread safe
545   // Add the message to the end of the queue
546   // Signal for the multiplexer to return
547 
548   {
549     CritScope cs(&crit_);
550     Message msg;
551     msg.posted_from = posted_from;
552     msg.phandler = phandler;
553     msg.message_id = id;
554     msg.pdata = pdata;
555     messages_.push_back(msg);
556   }
557   WakeUpSocketServer();
558 }
559 
PostDelayed(const Location & posted_from,int delay_ms,MessageHandler * phandler,uint32_t id,MessageData * pdata)560 void Thread::PostDelayed(const Location& posted_from,
561                          int delay_ms,
562                          MessageHandler* phandler,
563                          uint32_t id,
564                          MessageData* pdata) {
565   return DoDelayPost(posted_from, delay_ms, TimeAfter(delay_ms), phandler, id,
566                      pdata);
567 }
568 
PostAt(const Location & posted_from,int64_t run_at_ms,MessageHandler * phandler,uint32_t id,MessageData * pdata)569 void Thread::PostAt(const Location& posted_from,
570                     int64_t run_at_ms,
571                     MessageHandler* phandler,
572                     uint32_t id,
573                     MessageData* pdata) {
574   return DoDelayPost(posted_from, TimeUntil(run_at_ms), run_at_ms, phandler, id,
575                      pdata);
576 }
577 
DoDelayPost(const Location & posted_from,int64_t delay_ms,int64_t run_at_ms,MessageHandler * phandler,uint32_t id,MessageData * pdata)578 void Thread::DoDelayPost(const Location& posted_from,
579                          int64_t delay_ms,
580                          int64_t run_at_ms,
581                          MessageHandler* phandler,
582                          uint32_t id,
583                          MessageData* pdata) {
584   if (IsQuitting()) {
585     delete pdata;
586     return;
587   }
588 
589   // Keep thread safe
590   // Add to the priority queue. Gets sorted soonest first.
591   // Signal for the multiplexer to return.
592 
593   {
594     CritScope cs(&crit_);
595     Message msg;
596     msg.posted_from = posted_from;
597     msg.phandler = phandler;
598     msg.message_id = id;
599     msg.pdata = pdata;
600     DelayedMessage delayed(delay_ms, run_at_ms, delayed_next_num_, msg);
601     delayed_messages_.push(delayed);
602     // If this message queue processes 1 message every millisecond for 50 days,
603     // we will wrap this number.  Even then, only messages with identical times
604     // will be misordered, and then only briefly.  This is probably ok.
605     ++delayed_next_num_;
606     RTC_DCHECK_NE(0, delayed_next_num_);
607   }
608   WakeUpSocketServer();
609 }
610 
GetDelay()611 int Thread::GetDelay() {
612   CritScope cs(&crit_);
613 
614   if (!messages_.empty())
615     return 0;
616 
617   if (!delayed_messages_.empty()) {
618     int delay = TimeUntil(delayed_messages_.top().run_time_ms_);
619     if (delay < 0)
620       delay = 0;
621     return delay;
622   }
623 
624   return kForever;
625 }
626 
ClearInternal(MessageHandler * phandler,uint32_t id,MessageList * removed)627 void Thread::ClearInternal(MessageHandler* phandler,
628                            uint32_t id,
629                            MessageList* removed) {
630   // Remove messages with phandler
631 
632   if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
633     if (removed) {
634       removed->push_back(msgPeek_);
635     } else {
636       delete msgPeek_.pdata;
637     }
638     fPeekKeep_ = false;
639   }
640 
641   // Remove from ordered message queue
642 
643   for (auto it = messages_.begin(); it != messages_.end();) {
644     if (it->Match(phandler, id)) {
645       if (removed) {
646         removed->push_back(*it);
647       } else {
648         delete it->pdata;
649       }
650       it = messages_.erase(it);
651     } else {
652       ++it;
653     }
654   }
655 
656   // Remove from priority queue. Not directly iterable, so use this approach
657 
658   auto new_end = delayed_messages_.container().begin();
659   for (auto it = new_end; it != delayed_messages_.container().end(); ++it) {
660     if (it->msg_.Match(phandler, id)) {
661       if (removed) {
662         removed->push_back(it->msg_);
663       } else {
664         delete it->msg_.pdata;
665       }
666     } else {
667       *new_end++ = *it;
668     }
669   }
670   delayed_messages_.container().erase(new_end,
671                                       delayed_messages_.container().end());
672   delayed_messages_.reheap();
673 }
674 
Dispatch(Message * pmsg)675 void Thread::Dispatch(Message* pmsg) {
676   TRACE_EVENT2("webrtc", "Thread::Dispatch", "src_file",
677                pmsg->posted_from.file_name(), "src_func",
678                pmsg->posted_from.function_name());
679   int64_t start_time = TimeMillis();
680   pmsg->phandler->OnMessage(pmsg);
681   int64_t end_time = TimeMillis();
682   int64_t diff = TimeDiff(end_time, start_time);
683   if (diff >= kSlowDispatchLoggingThreshold) {
684     RTC_LOG(LS_INFO) << "Message took " << diff
685                      << "ms to dispatch. Posted from: "
686                      << pmsg->posted_from.ToString();
687   }
688 }
689 
IsCurrent() const690 bool Thread::IsCurrent() const {
691   return ThreadManager::Instance()->CurrentThread() == this;
692 }
693 
CreateWithSocketServer()694 std::unique_ptr<Thread> Thread::CreateWithSocketServer() {
695   return std::unique_ptr<Thread>(new Thread(SocketServer::CreateDefault()));
696 }
697 
Create()698 std::unique_ptr<Thread> Thread::Create() {
699   return std::unique_ptr<Thread>(
700       new Thread(std::unique_ptr<SocketServer>(new NullSocketServer())));
701 }
702 
SleepMs(int milliseconds)703 bool Thread::SleepMs(int milliseconds) {
704   AssertBlockingIsAllowedOnCurrentThread();
705 
706 #if defined(WEBRTC_WIN)
707   ::Sleep(milliseconds);
708   return true;
709 #else
710   // POSIX has both a usleep() and a nanosleep(), but the former is deprecated,
711   // so we use nanosleep() even though it has greater precision than necessary.
712   struct timespec ts;
713   ts.tv_sec = milliseconds / 1000;
714   ts.tv_nsec = (milliseconds % 1000) * 1000000;
715   int ret = nanosleep(&ts, nullptr);
716   if (ret != 0) {
717     RTC_LOG_ERR(LS_WARNING) << "nanosleep() returning early";
718     return false;
719   }
720   return true;
721 #endif
722 }
723 
SetName(const std::string & name,const void * obj)724 bool Thread::SetName(const std::string& name, const void* obj) {
725   RTC_DCHECK(!IsRunning());
726 
727   name_ = name;
728   if (obj) {
729     // The %p specifier typically produce at most 16 hex digits, possibly with a
730     // 0x prefix. But format is implementation defined, so add some margin.
731     char buf[30];
732     snprintf(buf, sizeof(buf), " 0x%p", obj);
733     name_ += buf;
734   }
735   return true;
736 }
737 
Start()738 bool Thread::Start() {
739   RTC_DCHECK(!IsRunning());
740 
741   if (IsRunning())
742     return false;
743 
744   Restart();  // reset IsQuitting() if the thread is being restarted
745 
746   // Make sure that ThreadManager is created on the main thread before
747   // we start a new thread.
748   ThreadManager::Instance();
749 
750   owned_ = true;
751 
752 #if defined(WEBRTC_WIN)
753   thread_ = CreateThread(nullptr, 0, PreRun, this, 0, &thread_id_);
754   if (!thread_) {
755     return false;
756   }
757 #elif defined(WEBRTC_POSIX)
758   pthread_attr_t attr;
759   pthread_attr_init(&attr);
760 
761   int error_code = pthread_create(&thread_, &attr, PreRun, this);
762   if (0 != error_code) {
763     RTC_LOG(LS_ERROR) << "Unable to create pthread, error " << error_code;
764     thread_ = 0;
765     return false;
766   }
767   RTC_DCHECK(thread_);
768 #endif
769   return true;
770 }
771 
WrapCurrent()772 bool Thread::WrapCurrent() {
773   return WrapCurrentWithThreadManager(ThreadManager::Instance(), true);
774 }
775 
UnwrapCurrent()776 void Thread::UnwrapCurrent() {
777   // Clears the platform-specific thread-specific storage.
778   ThreadManager::Instance()->SetCurrentThread(nullptr);
779 #if defined(WEBRTC_WIN)
780   if (thread_ != nullptr) {
781     if (!CloseHandle(thread_)) {
782       RTC_LOG_GLE(LS_ERROR)
783           << "When unwrapping thread, failed to close handle.";
784     }
785     thread_ = nullptr;
786     thread_id_ = 0;
787   }
788 #elif defined(WEBRTC_POSIX)
789   thread_ = 0;
790 #endif
791 }
792 
SafeWrapCurrent()793 void Thread::SafeWrapCurrent() {
794   WrapCurrentWithThreadManager(ThreadManager::Instance(), false);
795 }
796 
Join()797 void Thread::Join() {
798   if (!IsRunning())
799     return;
800 
801   RTC_DCHECK(!IsCurrent());
802   if (Current() && !Current()->blocking_calls_allowed_) {
803     RTC_LOG(LS_WARNING) << "Waiting for the thread to join, "
804                            "but blocking calls have been disallowed";
805   }
806 
807 #if defined(WEBRTC_WIN)
808   RTC_DCHECK(thread_ != nullptr);
809   WaitForSingleObject(thread_, INFINITE);
810   CloseHandle(thread_);
811   thread_ = nullptr;
812   thread_id_ = 0;
813 #elif defined(WEBRTC_POSIX)
814   pthread_join(thread_, nullptr);
815   thread_ = 0;
816 #endif
817 }
818 
SetAllowBlockingCalls(bool allow)819 bool Thread::SetAllowBlockingCalls(bool allow) {
820   RTC_DCHECK(IsCurrent());
821   bool previous = blocking_calls_allowed_;
822   blocking_calls_allowed_ = allow;
823   return previous;
824 }
825 
826 // static
AssertBlockingIsAllowedOnCurrentThread()827 void Thread::AssertBlockingIsAllowedOnCurrentThread() {
828 #if !defined(NDEBUG)
829   Thread* current = Thread::Current();
830   RTC_DCHECK(!current || current->blocking_calls_allowed_);
831 #endif
832 }
833 
834 // static
835 #if defined(WEBRTC_WIN)
PreRun(LPVOID pv)836 DWORD WINAPI Thread::PreRun(LPVOID pv) {
837 #else
838 void* Thread::PreRun(void* pv) {
839 #endif
840   Thread* thread = static_cast<Thread*>(pv);
841   ThreadManager::Instance()->SetCurrentThread(thread);
842   rtc::SetCurrentThreadName(thread->name_.c_str());
843 #if defined(WEBRTC_MAC)
844   ScopedAutoReleasePool pool;
845 #endif
846   thread->Run();
847 
848   ThreadManager::Instance()->SetCurrentThread(nullptr);
849 #ifdef WEBRTC_WIN
850   return 0;
851 #else
852   return nullptr;
853 #endif
854 }  // namespace rtc
855 
856 void Thread::Run() {
857   ProcessMessages(kForever);
858 }
859 
860 bool Thread::IsOwned() {
861   RTC_DCHECK(IsRunning());
862   return owned_;
863 }
864 
865 void Thread::Stop() {
866   Thread::Quit();
867   Join();
868 }
869 
870 void Thread::Send(const Location& posted_from,
871                   MessageHandler* phandler,
872                   uint32_t id,
873                   MessageData* pdata) {
874   RTC_DCHECK(!IsQuitting());
875   if (IsQuitting())
876     return;
877 
878   // Sent messages are sent to the MessageHandler directly, in the context
879   // of "thread", like Win32 SendMessage. If in the right context,
880   // call the handler directly.
881   Message msg;
882   msg.posted_from = posted_from;
883   msg.phandler = phandler;
884   msg.message_id = id;
885   msg.pdata = pdata;
886   if (IsCurrent()) {
887     msg.phandler->OnMessage(&msg);
888     return;
889   }
890 
891   AssertBlockingIsAllowedOnCurrentThread();
892 
893   AutoThread thread;
894   Thread* current_thread = Thread::Current();
895   RTC_DCHECK(current_thread != nullptr);  // AutoThread ensures this
896   RTC_DCHECK(current_thread->IsInvokeToThreadAllowed(this));
897 #if RTC_DCHECK_IS_ON
898   ThreadManager::Instance()->RegisterSendAndCheckForCycles(current_thread,
899                                                            this);
900 #endif
901   bool ready = false;
902   PostTask(
903       webrtc::ToQueuedTask([msg]() mutable { msg.phandler->OnMessage(&msg); },
904                            [this, &ready, current_thread] {
905                              CritScope cs(&crit_);
906                              ready = true;
907                              current_thread->socketserver()->WakeUp();
908                            }));
909 
910   bool waited = false;
911   crit_.Enter();
912   while (!ready) {
913     crit_.Leave();
914     current_thread->socketserver()->Wait(kForever, false);
915     waited = true;
916     crit_.Enter();
917   }
918   crit_.Leave();
919 
920   // Our Wait loop above may have consumed some WakeUp events for this
921   // Thread, that weren't relevant to this Send.  Losing these WakeUps can
922   // cause problems for some SocketServers.
923   //
924   // Concrete example:
925   // Win32SocketServer on thread A calls Send on thread B.  While processing the
926   // message, thread B Posts a message to A.  We consume the wakeup for that
927   // Post while waiting for the Send to complete, which means that when we exit
928   // this loop, we need to issue another WakeUp, or else the Posted message
929   // won't be processed in a timely manner.
930 
931   if (waited) {
932     current_thread->socketserver()->WakeUp();
933   }
934 }
935 
936 void Thread::InvokeInternal(const Location& posted_from,
937                             rtc::FunctionView<void()> functor) {
938   TRACE_EVENT2("webrtc", "Thread::Invoke", "src_file", posted_from.file_name(),
939                "src_func", posted_from.function_name());
940 
941   class FunctorMessageHandler : public MessageHandler {
942    public:
943     explicit FunctorMessageHandler(rtc::FunctionView<void()> functor)
944         : functor_(functor) {}
945     void OnMessage(Message* msg) override { functor_(); }
946 
947    private:
948     rtc::FunctionView<void()> functor_;
949   } handler(functor);
950 
951   Send(posted_from, &handler);
952 }
953 
954 // Called by the ThreadManager when being set as the current thread.
955 void Thread::EnsureIsCurrentTaskQueue() {
956   task_queue_registration_ =
957       std::make_unique<TaskQueueBase::CurrentTaskQueueSetter>(this);
958 }
959 
960 // Called by the ThreadManager when being set as the current thread.
961 void Thread::ClearCurrentTaskQueue() {
962   task_queue_registration_.reset();
963 }
964 
965 void Thread::QueuedTaskHandler::OnMessage(Message* msg) {
966   RTC_DCHECK(msg);
967   auto* data = static_cast<ScopedMessageData<webrtc::QueuedTask>*>(msg->pdata);
968   std::unique_ptr<webrtc::QueuedTask> task = std::move(data->data());
969   // Thread expects handler to own Message::pdata when OnMessage is called
970   // Since MessageData is no longer needed, delete it.
971   delete data;
972 
973   // QueuedTask interface uses Run return value to communicate who owns the
974   // task. false means QueuedTask took the ownership.
975   if (!task->Run())
976     task.release();
977 }
978 
979 void Thread::AllowInvokesToThread(Thread* thread) {
980 #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
981   if (!IsCurrent()) {
982     PostTask(webrtc::ToQueuedTask(
983         [thread, this]() { AllowInvokesToThread(thread); }));
984     return;
985   }
986   RTC_DCHECK_RUN_ON(this);
987   allowed_threads_.push_back(thread);
988   invoke_policy_enabled_ = true;
989 #endif
990 }
991 
992 void Thread::DisallowAllInvokes() {
993 #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
994   if (!IsCurrent()) {
995     PostTask(webrtc::ToQueuedTask([this]() { DisallowAllInvokes(); }));
996     return;
997   }
998   RTC_DCHECK_RUN_ON(this);
999   allowed_threads_.clear();
1000   invoke_policy_enabled_ = true;
1001 #endif
1002 }
1003 
1004 // Returns true if no policies added or if there is at least one policy
1005 // that permits invocation to |target| thread.
1006 bool Thread::IsInvokeToThreadAllowed(rtc::Thread* target) {
1007 #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
1008   RTC_DCHECK_RUN_ON(this);
1009   if (!invoke_policy_enabled_) {
1010     return true;
1011   }
1012   for (const auto* thread : allowed_threads_) {
1013     if (thread == target) {
1014       return true;
1015     }
1016   }
1017   return false;
1018 #else
1019   return true;
1020 #endif
1021 }
1022 
1023 void Thread::PostTask(std::unique_ptr<webrtc::QueuedTask> task) {
1024   // Though Post takes MessageData by raw pointer (last parameter), it still
1025   // takes it with ownership.
1026   Post(RTC_FROM_HERE, &queued_task_handler_,
1027        /*id=*/0, new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1028 }
1029 
1030 void Thread::PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
1031                              uint32_t milliseconds) {
1032   // Though PostDelayed takes MessageData by raw pointer (last parameter),
1033   // it still takes it with ownership.
1034   PostDelayed(RTC_FROM_HERE, milliseconds, &queued_task_handler_,
1035               /*id=*/0,
1036               new ScopedMessageData<webrtc::QueuedTask>(std::move(task)));
1037 }
1038 
1039 void Thread::Delete() {
1040   Stop();
1041   delete this;
1042 }
1043 
1044 bool Thread::IsProcessingMessagesForTesting() {
1045   return (owned_ || IsCurrent()) && !IsQuitting();
1046 }
1047 
1048 void Thread::Clear(MessageHandler* phandler,
1049                    uint32_t id,
1050                    MessageList* removed) {
1051   CritScope cs(&crit_);
1052   ClearInternal(phandler, id, removed);
1053 }
1054 
1055 bool Thread::ProcessMessages(int cmsLoop) {
1056   // Using ProcessMessages with a custom clock for testing and a time greater
1057   // than 0 doesn't work, since it's not guaranteed to advance the custom
1058   // clock's time, and may get stuck in an infinite loop.
1059   RTC_DCHECK(GetClockForTesting() == nullptr || cmsLoop == 0 ||
1060              cmsLoop == kForever);
1061   int64_t msEnd = (kForever == cmsLoop) ? 0 : TimeAfter(cmsLoop);
1062   int cmsNext = cmsLoop;
1063 
1064   while (true) {
1065 #if defined(WEBRTC_MAC)
1066     ScopedAutoReleasePool pool;
1067 #endif
1068     Message msg;
1069     if (!Get(&msg, cmsNext))
1070       return !IsQuitting();
1071     Dispatch(&msg);
1072 
1073     if (cmsLoop != kForever) {
1074       cmsNext = static_cast<int>(TimeUntil(msEnd));
1075       if (cmsNext < 0)
1076         return true;
1077     }
1078   }
1079 }
1080 
1081 bool Thread::WrapCurrentWithThreadManager(ThreadManager* thread_manager,
1082                                           bool need_synchronize_access) {
1083   RTC_DCHECK(!IsRunning());
1084 
1085 #if defined(WEBRTC_WIN)
1086   if (need_synchronize_access) {
1087     // We explicitly ask for no rights other than synchronization.
1088     // This gives us the best chance of succeeding.
1089     thread_ = OpenThread(SYNCHRONIZE, FALSE, GetCurrentThreadId());
1090     if (!thread_) {
1091       RTC_LOG_GLE(LS_ERROR) << "Unable to get handle to thread.";
1092       return false;
1093     }
1094     thread_id_ = GetCurrentThreadId();
1095   }
1096 #elif defined(WEBRTC_POSIX)
1097   thread_ = pthread_self();
1098 #endif
1099   owned_ = false;
1100   thread_manager->SetCurrentThread(this);
1101   return true;
1102 }
1103 
1104 bool Thread::IsRunning() {
1105 #if defined(WEBRTC_WIN)
1106   return thread_ != nullptr;
1107 #elif defined(WEBRTC_POSIX)
1108   return thread_ != 0;
1109 #endif
1110 }
1111 
1112 // static
1113 MessageHandler* Thread::GetPostTaskMessageHandler() {
1114   // Allocate at first call, never deallocate.
1115   static MessageHandler* handler = new MessageHandlerWithTask;
1116   return handler;
1117 }
1118 
1119 AutoThread::AutoThread()
1120     : Thread(SocketServer::CreateDefault(), /*do_init=*/false) {
1121   if (!ThreadManager::Instance()->CurrentThread()) {
1122     // DoInit registers with ThreadManager. Do that only if we intend to
1123     // be rtc::Thread::Current(), otherwise ProcessAllMessageQueuesInternal will
1124     // post a message to a queue that no running thread is serving.
1125     DoInit();
1126     ThreadManager::Instance()->SetCurrentThread(this);
1127   }
1128 }
1129 
1130 AutoThread::~AutoThread() {
1131   Stop();
1132   DoDestroy();
1133   if (ThreadManager::Instance()->CurrentThread() == this) {
1134     ThreadManager::Instance()->SetCurrentThread(nullptr);
1135   }
1136 }
1137 
1138 AutoSocketServerThread::AutoSocketServerThread(SocketServer* ss)
1139     : Thread(ss, /*do_init=*/false) {
1140   DoInit();
1141   old_thread_ = ThreadManager::Instance()->CurrentThread();
1142   // Temporarily set the current thread to nullptr so that we can keep checks
1143   // around that catch unintentional pointer overwrites.
1144   rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
1145   rtc::ThreadManager::Instance()->SetCurrentThread(this);
1146   if (old_thread_) {
1147     ThreadManager::Remove(old_thread_);
1148   }
1149 }
1150 
1151 AutoSocketServerThread::~AutoSocketServerThread() {
1152   RTC_DCHECK(ThreadManager::Instance()->CurrentThread() == this);
1153   // Some tests post destroy messages to this thread. To avoid memory
1154   // leaks, we have to process those messages. In particular
1155   // P2PTransportChannelPingTest, relying on the message posted in
1156   // cricket::Connection::Destroy.
1157   ProcessMessages(0);
1158   // Stop and destroy the thread before clearing it as the current thread.
1159   // Sometimes there are messages left in the Thread that will be
1160   // destroyed by DoDestroy, and sometimes the destructors of the message and/or
1161   // its contents rely on this thread still being set as the current thread.
1162   Stop();
1163   DoDestroy();
1164   rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
1165   rtc::ThreadManager::Instance()->SetCurrentThread(old_thread_);
1166   if (old_thread_) {
1167     ThreadManager::Add(old_thread_);
1168   }
1169 }
1170 
1171 }  // namespace rtc
1172