forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipc_mojo_bootstrap.cc
1428 lines (1190 loc) · 48 KB
/
ipc_mojo_bootstrap.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ipc/ipc_mojo_bootstrap.h"
#include <inttypes.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <utility>
#include <vector>
#include "base/check_op.h"
#include "base/containers/circular_deque.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/not_fatal_until.h"
#include "base/ranges/algorithm.h"
#include "base/sequence_checker.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/common/task_annotator.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/thread_annotations.h"
#include "base/trace_event/memory_allocator_dump.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/typed_macros.h"
#include "ipc/ipc_channel.h"
#include "ipc/urgent_message_observer.h"
#include "mojo/public/c/system/types.h"
#include "mojo/public/cpp/bindings/associated_group.h"
#include "mojo/public/cpp/bindings/associated_group_controller.h"
#include "mojo/public/cpp/bindings/connector.h"
#include "mojo/public/cpp/bindings/features.h"
#include "mojo/public/cpp/bindings/interface_endpoint_client.h"
#include "mojo/public/cpp/bindings/interface_endpoint_controller.h"
#include "mojo/public/cpp/bindings/interface_id.h"
#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/bindings/message_header_validator.h"
#include "mojo/public/cpp/bindings/mojo_buildflags.h"
#include "mojo/public/cpp/bindings/pipe_control_message_handler.h"
#include "mojo/public/cpp/bindings/pipe_control_message_handler_delegate.h"
#include "mojo/public/cpp/bindings/pipe_control_message_proxy.h"
#include "mojo/public/cpp/bindings/scoped_message_error_crash_key.h"
#include "mojo/public/cpp/bindings/sequence_local_sync_event_watcher.h"
#include "mojo/public/cpp/bindings/tracing_helpers.h"
namespace IPC {
class ChannelAssociatedGroupController;
namespace {
constinit thread_local bool off_sequence_binding_allowed = false;
BASE_FEATURE(kMojoChannelAssociatedSendUsesRunOrPostTask,
"MojoChannelAssociatedSendUsesRunOrPostTask",
base::FEATURE_DISABLED_BY_DEFAULT);
// Used to track some internal Channel state in pursuit of message leaks.
//
// TODO(crbug.com/40563310): Remove this.
class ControllerMemoryDumpProvider
: public base::trace_event::MemoryDumpProvider {
public:
ControllerMemoryDumpProvider() {
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
this, "IPCChannel", nullptr);
}
ControllerMemoryDumpProvider(const ControllerMemoryDumpProvider&) = delete;
ControllerMemoryDumpProvider& operator=(const ControllerMemoryDumpProvider&) =
delete;
~ControllerMemoryDumpProvider() override {
base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
this);
}
void AddController(ChannelAssociatedGroupController* controller) {
base::AutoLock lock(lock_);
controllers_.insert(controller);
}
void RemoveController(ChannelAssociatedGroupController* controller) {
base::AutoLock lock(lock_);
controllers_.erase(controller);
}
// base::trace_event::MemoryDumpProvider:
bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) override;
private:
base::Lock lock_;
std::set<raw_ptr<ChannelAssociatedGroupController, SetExperimental>>
controllers_;
};
ControllerMemoryDumpProvider& GetMemoryDumpProvider() {
static base::NoDestructor<ControllerMemoryDumpProvider> provider;
return *provider;
}
// Messages are grouped by this info when recording memory metrics.
struct MessageMemoryDumpInfo {
MessageMemoryDumpInfo(const mojo::Message& message)
: id(message.name()), profiler_tag(message.heap_profiler_tag()) {}
MessageMemoryDumpInfo() = default;
bool operator==(const MessageMemoryDumpInfo& other) const {
return other.id == id && other.profiler_tag == profiler_tag;
}
uint32_t id = 0;
const char* profiler_tag = nullptr;
};
struct MessageMemoryDumpInfoHash {
size_t operator()(const MessageMemoryDumpInfo& info) const {
return base::HashInts(
info.id, info.profiler_tag ? base::FastHash(info.profiler_tag) : 0);
}
};
class ScopedUrgentMessageNotification {
public:
explicit ScopedUrgentMessageNotification(
UrgentMessageObserver* observer = nullptr)
: observer_(observer) {
if (observer_) {
observer_->OnUrgentMessageReceived();
}
}
~ScopedUrgentMessageNotification() {
if (observer_) {
observer_->OnUrgentMessageProcessed();
}
}
ScopedUrgentMessageNotification(ScopedUrgentMessageNotification&& other)
: observer_(std::exchange(other.observer_, nullptr)) {}
ScopedUrgentMessageNotification& operator=(
ScopedUrgentMessageNotification&& other) {
observer_ = std::exchange(other.observer_, nullptr);
return *this;
}
private:
raw_ptr<UrgentMessageObserver> observer_;
};
} // namespace
class ChannelAssociatedGroupController
: public mojo::AssociatedGroupController,
public mojo::MessageReceiver,
public mojo::PipeControlMessageHandlerDelegate {
public:
ChannelAssociatedGroupController(
bool set_interface_id_namespace_bit,
const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& proxy_task_runner)
: task_runner_(ipc_task_runner),
proxy_task_runner_(proxy_task_runner),
set_interface_id_namespace_bit_(set_interface_id_namespace_bit),
dispatcher_(this),
control_message_handler_(this),
control_message_proxy_thunk_(this),
control_message_proxy_(&control_message_proxy_thunk_) {
control_message_handler_.SetDescription(
"IPC::mojom::Bootstrap [primary] PipeControlMessageHandler");
dispatcher_.SetValidator(std::make_unique<mojo::MessageHeaderValidator>(
"IPC::mojom::Bootstrap [primary] MessageHeaderValidator"));
GetMemoryDumpProvider().AddController(this);
DETACH_FROM_SEQUENCE(sequence_checker_);
}
ChannelAssociatedGroupController(const ChannelAssociatedGroupController&) =
delete;
ChannelAssociatedGroupController& operator=(
const ChannelAssociatedGroupController&) = delete;
size_t GetQueuedMessageCount() {
base::AutoLock lock(outgoing_messages_lock_);
return outgoing_messages_.size();
}
void GetTopQueuedMessageMemoryDumpInfo(MessageMemoryDumpInfo* info,
size_t* count) {
std::unordered_map<MessageMemoryDumpInfo, size_t, MessageMemoryDumpInfoHash>
counts;
std::pair<MessageMemoryDumpInfo, size_t> top_message_info_and_count = {
MessageMemoryDumpInfo(), 0};
base::AutoLock lock(outgoing_messages_lock_);
for (const auto& message : outgoing_messages_) {
auto it_and_inserted = counts.emplace(MessageMemoryDumpInfo(message), 0);
it_and_inserted.first->second++;
if (it_and_inserted.first->second > top_message_info_and_count.second)
top_message_info_and_count = *it_and_inserted.first;
}
*info = top_message_info_and_count.first;
*count = top_message_info_and_count.second;
}
void Pause() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CHECK(was_bound_or_message_sent_);
CHECK(!paused_);
paused_ = true;
}
void Unpause() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CHECK(was_bound_or_message_sent_);
CHECK(paused_);
paused_ = false;
}
void FlushOutgoingMessages() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CHECK(was_bound_or_message_sent_);
std::vector<mojo::Message> outgoing_messages;
{
base::AutoLock lock(outgoing_messages_lock_);
std::swap(outgoing_messages, outgoing_messages_);
}
for (auto& message : outgoing_messages)
SendMessage(&message);
}
void Bind(mojo::ScopedMessagePipeHandle handle,
mojo::PendingAssociatedRemote<mojom::Channel>* sender,
mojo::PendingAssociatedReceiver<mojom::Channel>* receiver) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
connector_ = std::make_unique<mojo::Connector>(
std::move(handle), mojo::Connector::SINGLE_THREADED_SEND,
"IPC Channel");
connector_->set_incoming_receiver(&dispatcher_);
connector_->set_connection_error_handler(
base::BindOnce(&ChannelAssociatedGroupController::OnPipeError,
base::Unretained(this)));
connector_->set_enforce_errors_from_incoming_receiver(false);
// Don't let the Connector do any sort of queuing on our behalf. Individual
// messages bound for the IPC::ChannelProxy thread (i.e. that vast majority
// of messages received by this Connector) are already individually
// scheduled for dispatch by ChannelProxy, so Connector's normal mode of
// operation would only introduce a redundant scheduling step for most
// messages.
connector_->set_force_immediate_dispatch(true);
mojo::InterfaceId sender_id, receiver_id;
if (set_interface_id_namespace_bit_) {
sender_id = 1 | mojo::kInterfaceIdNamespaceMask;
receiver_id = 1;
} else {
sender_id = 1;
receiver_id = 1 | mojo::kInterfaceIdNamespaceMask;
}
{
base::AutoLock locker(lock_);
Endpoint* sender_endpoint = new Endpoint(this, sender_id);
Endpoint* receiver_endpoint = new Endpoint(this, receiver_id);
endpoints_.insert({ sender_id, sender_endpoint });
endpoints_.insert({ receiver_id, receiver_endpoint });
sender_endpoint->set_handle_created();
receiver_endpoint->set_handle_created();
}
mojo::ScopedInterfaceEndpointHandle sender_handle =
CreateScopedInterfaceEndpointHandle(sender_id);
mojo::ScopedInterfaceEndpointHandle receiver_handle =
CreateScopedInterfaceEndpointHandle(receiver_id);
*sender = mojo::PendingAssociatedRemote<mojom::Channel>(
std::move(sender_handle), 0);
*receiver = mojo::PendingAssociatedReceiver<mojom::Channel>(
std::move(receiver_handle));
if (!was_bound_or_message_sent_) {
was_bound_or_message_sent_ = true;
DETACH_FROM_SEQUENCE(sequence_checker_);
}
}
void StartReceiving() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CHECK(was_bound_or_message_sent_);
connector_->StartReceiving(task_runner_);
}
void ShutDown() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
shut_down_ = true;
if (connector_)
connector_->CloseMessagePipe();
OnPipeError();
connector_.reset();
base::AutoLock lock(outgoing_messages_lock_);
outgoing_messages_.clear();
}
// mojo::AssociatedGroupController:
mojo::InterfaceId AssociateInterface(
mojo::ScopedInterfaceEndpointHandle handle_to_send) override {
if (!handle_to_send.pending_association())
return mojo::kInvalidInterfaceId;
uint32_t id = 0;
{
base::AutoLock locker(lock_);
do {
if (next_interface_id_ >= mojo::kInterfaceIdNamespaceMask)
next_interface_id_ = 2;
id = next_interface_id_++;
if (set_interface_id_namespace_bit_)
id |= mojo::kInterfaceIdNamespaceMask;
} while (base::Contains(endpoints_, id));
Endpoint* endpoint = new Endpoint(this, id);
if (encountered_error_)
endpoint->set_peer_closed();
endpoint->set_handle_created();
endpoints_.insert({id, endpoint});
}
if (!NotifyAssociation(&handle_to_send, id)) {
// The peer handle of |handle_to_send|, which is supposed to join this
// associated group, has been closed.
{
base::AutoLock locker(lock_);
Endpoint* endpoint = FindEndpoint(id);
if (endpoint)
MarkClosedAndMaybeRemove(endpoint);
}
control_message_proxy_.NotifyPeerEndpointClosed(
id, handle_to_send.disconnect_reason());
}
return id;
}
mojo::ScopedInterfaceEndpointHandle CreateLocalEndpointHandle(
mojo::InterfaceId id) override {
if (!mojo::IsValidInterfaceId(id))
return mojo::ScopedInterfaceEndpointHandle();
// Unless it is the primary ID, |id| is from the remote side and therefore
// its namespace bit is supposed to be different than the value that this
// router would use.
if (!mojo::IsPrimaryInterfaceId(id) &&
set_interface_id_namespace_bit_ ==
mojo::HasInterfaceIdNamespaceBitSet(id)) {
return mojo::ScopedInterfaceEndpointHandle();
}
base::AutoLock locker(lock_);
bool inserted = false;
Endpoint* endpoint = FindOrInsertEndpoint(id, &inserted);
if (inserted) {
DCHECK(!endpoint->handle_created());
if (encountered_error_)
endpoint->set_peer_closed();
} else {
if (endpoint->handle_created())
return mojo::ScopedInterfaceEndpointHandle();
}
endpoint->set_handle_created();
return CreateScopedInterfaceEndpointHandle(id);
}
void CloseEndpointHandle(
mojo::InterfaceId id,
const std::optional<mojo::DisconnectReason>& reason) override {
if (!mojo::IsValidInterfaceId(id))
return;
{
base::AutoLock locker(lock_);
DCHECK(base::Contains(endpoints_, id));
Endpoint* endpoint = endpoints_[id].get();
DCHECK(!endpoint->client());
DCHECK(!endpoint->closed());
MarkClosedAndMaybeRemove(endpoint);
}
if (!mojo::IsPrimaryInterfaceId(id) || reason)
control_message_proxy_.NotifyPeerEndpointClosed(id, reason);
}
void NotifyLocalEndpointOfPeerClosure(mojo::InterfaceId id) override {
if (!task_runner_->RunsTasksInCurrentSequence()) {
task_runner_->PostTask(
FROM_HERE, base::BindOnce(&ChannelAssociatedGroupController::
NotifyLocalEndpointOfPeerClosure,
base::WrapRefCounted(this), id));
return;
}
OnPeerAssociatedEndpointClosed(id, std::nullopt);
}
mojo::InterfaceEndpointController* AttachEndpointClient(
const mojo::ScopedInterfaceEndpointHandle& handle,
mojo::InterfaceEndpointClient* client,
scoped_refptr<base::SequencedTaskRunner> runner) override {
const mojo::InterfaceId id = handle.id();
DCHECK(mojo::IsValidInterfaceId(id));
DCHECK(client);
base::AutoLock locker(lock_);
DCHECK(base::Contains(endpoints_, id));
Endpoint* endpoint = endpoints_[id].get();
endpoint->AttachClient(client, std::move(runner));
if (endpoint->peer_closed())
NotifyEndpointOfError(endpoint, true /* force_async */);
return endpoint;
}
void DetachEndpointClient(
const mojo::ScopedInterfaceEndpointHandle& handle) override {
const mojo::InterfaceId id = handle.id();
DCHECK(mojo::IsValidInterfaceId(id));
base::AutoLock locker(lock_);
DCHECK(base::Contains(endpoints_, id));
Endpoint* endpoint = endpoints_[id].get();
endpoint->DetachClient();
}
void RaiseError() override {
// We ignore errors on channel endpoints, leaving the pipe open. There are
// good reasons for this:
//
// * We should never close a channel endpoint in either process as long as
// the child process is still alive. The child's endpoint should only be
// closed implicitly by process death, and the browser's endpoint should
// only be closed after the child process is confirmed to be dead. Crash
// reporting logic in Chrome relies on this behavior in order to do the
// right thing.
//
// * There are two interesting conditions under which RaiseError() can be
// implicitly reached: an incoming message fails validation, or the
// local endpoint drops a response callback without calling it.
//
// * In the validation case, we also report the message as bad, and this
// will imminently trigger the common bad-IPC path in the browser,
// causing the browser to kill the offending renderer.
//
// * In the dropped response callback case, the net result of ignoring the
// issue is generally innocuous. While indicative of programmer error,
// it's not a severe failure and is already covered by separate DCHECKs.
//
// See https://crbug.com/861607 for additional discussion.
}
bool PrefersSerializedMessages() override { return true; }
void SetUrgentMessageObserver(UrgentMessageObserver* observer) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CHECK(!was_bound_or_message_sent_);
urgent_message_observer_ = observer;
DETACH_FROM_SEQUENCE(sequence_checker_);
}
private:
class Endpoint;
class ControlMessageProxyThunk;
friend class Endpoint;
friend class ControlMessageProxyThunk;
// MessageWrapper objects are always destroyed under the controller's lock. On
// destruction, if the message it wrappers contains
// ScopedInterfaceEndpointHandles (which cannot be destructed under the
// controller's lock), the wrapper unlocks to clean them up.
class MessageWrapper {
public:
MessageWrapper() = default;
MessageWrapper(ChannelAssociatedGroupController* controller,
mojo::Message message)
: controller_(controller), value_(std::move(message)) {}
MessageWrapper(MessageWrapper&& other)
: controller_(other.controller_), value_(std::move(other.value_)) {}
MessageWrapper(const MessageWrapper&) = delete;
MessageWrapper& operator=(const MessageWrapper&) = delete;
~MessageWrapper() {
if (value_.associated_endpoint_handles()->empty())
return;
controller_->lock_.AssertAcquired();
{
base::AutoUnlock unlocker(controller_->lock_);
value_.mutable_associated_endpoint_handles()->clear();
}
}
MessageWrapper& operator=(MessageWrapper&& other) {
controller_ = other.controller_;
value_ = std::move(other.value_);
return *this;
}
bool HasRequestId(uint64_t request_id) {
return !value_.IsNull() && value_.version() >= 1 &&
value_.header_v1()->request_id == request_id;
}
mojo::Message& value() { return value_; }
private:
raw_ptr<ChannelAssociatedGroupController> controller_ = nullptr;
mojo::Message value_;
};
class Endpoint : public base::RefCountedThreadSafe<Endpoint>,
public mojo::InterfaceEndpointController {
public:
Endpoint(ChannelAssociatedGroupController* controller, mojo::InterfaceId id)
: controller_(controller), id_(id) {}
Endpoint(const Endpoint&) = delete;
Endpoint& operator=(const Endpoint&) = delete;
mojo::InterfaceId id() const { return id_; }
bool closed() const {
controller_->lock_.AssertAcquired();
return closed_;
}
void set_closed() {
controller_->lock_.AssertAcquired();
closed_ = true;
}
bool peer_closed() const {
controller_->lock_.AssertAcquired();
return peer_closed_;
}
void set_peer_closed() {
controller_->lock_.AssertAcquired();
peer_closed_ = true;
}
bool handle_created() const {
controller_->lock_.AssertAcquired();
return handle_created_;
}
void set_handle_created() {
controller_->lock_.AssertAcquired();
handle_created_ = true;
}
const std::optional<mojo::DisconnectReason>& disconnect_reason() const {
return disconnect_reason_;
}
void set_disconnect_reason(
const std::optional<mojo::DisconnectReason>& disconnect_reason) {
disconnect_reason_ = disconnect_reason;
}
base::SequencedTaskRunner* task_runner() const {
return task_runner_.get();
}
bool was_bound_off_sequence() const { return was_bound_off_sequence_; }
mojo::InterfaceEndpointClient* client() const {
controller_->lock_.AssertAcquired();
return client_;
}
void AttachClient(mojo::InterfaceEndpointClient* client,
scoped_refptr<base::SequencedTaskRunner> runner) {
controller_->lock_.AssertAcquired();
DCHECK(!client_);
DCHECK(!closed_);
task_runner_ = std::move(runner);
client_ = client;
if (off_sequence_binding_allowed) {
was_bound_off_sequence_ = true;
}
}
void DetachClient() {
controller_->lock_.AssertAcquired();
DCHECK(client_);
DCHECK(!closed_);
task_runner_ = nullptr;
client_ = nullptr;
sync_watcher_.reset();
}
std::optional<uint32_t> EnqueueSyncMessage(MessageWrapper message) {
controller_->lock_.AssertAcquired();
if (exclusive_wait_ && exclusive_wait_->TryFulfillingWith(message)) {
exclusive_wait_ = nullptr;
return std::nullopt;
}
uint32_t id = GenerateSyncMessageId();
sync_messages_.emplace_back(id, std::move(message));
SignalSyncMessageEvent();
return id;
}
void SignalSyncMessageEvent() {
controller_->lock_.AssertAcquired();
if (sync_watcher_)
sync_watcher_->SignalEvent();
}
MessageWrapper PopSyncMessage(uint32_t id) {
controller_->lock_.AssertAcquired();
if (sync_messages_.empty() || sync_messages_.front().first != id)
return MessageWrapper();
MessageWrapper message = std::move(sync_messages_.front().second);
sync_messages_.pop_front();
return message;
}
// mojo::InterfaceEndpointController:
bool SendMessage(mojo::Message* message) override {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
message->set_interface_id(id_);
return controller_->SendMessage(message);
}
void AllowWokenUpBySyncWatchOnSameThread() override {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
EnsureSyncWatcherExists();
sync_watcher_->AllowWokenUpBySyncWatchOnSameSequence();
}
bool SyncWatch(const bool& should_stop) override {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
// It's not legal to make sync calls from the primary endpoint's thread,
// and in fact they must only happen from the proxy task runner.
DCHECK(!controller_->task_runner_->BelongsToCurrentThread());
DCHECK(controller_->proxy_task_runner_->BelongsToCurrentThread());
EnsureSyncWatcherExists();
{
base::AutoLock locker(controller_->lock_);
if (peer_closed_) {
SignalSyncMessageEvent();
}
}
return sync_watcher_->SyncWatch(&should_stop);
}
MessageWrapper WaitForIncomingSyncReply(uint64_t request_id) {
std::optional<ExclusiveSyncWait> wait;
{
base::AutoLock lock(controller_->lock_);
for (auto& [id, message] : sync_messages_) {
if (message.HasRequestId(request_id)) {
return std::move(message);
}
}
DCHECK(!exclusive_wait_);
wait.emplace(request_id);
exclusive_wait_ = &wait.value();
}
wait->event.Wait();
return std::move(wait->message);
}
bool SyncWatchExclusive(uint64_t request_id) override {
MessageWrapper message = WaitForIncomingSyncReply(request_id);
if (message.value().IsNull() || !client_) {
return false;
}
if (!client_->HandleIncomingMessage(&message.value())) {
base::AutoLock locker(controller_->lock_);
controller_->RaiseError();
return false;
}
return true;
}
void RegisterExternalSyncWaiter(uint64_t request_id) override {}
private:
friend class base::RefCountedThreadSafe<Endpoint>;
~Endpoint() override {
controller_->lock_.AssertAcquired();
DCHECK(!client_);
DCHECK(closed_);
DCHECK(peer_closed_);
DCHECK(!sync_watcher_);
if (exclusive_wait_) {
exclusive_wait_->event.Signal();
}
}
void OnSyncMessageEventReady() {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
// SUBTLE: The order of these scoped_refptrs matters.
// `controller_keepalive` MUST outlive `keepalive` because the Endpoint
// holds raw pointer to the AssociatedGroupController.
scoped_refptr<AssociatedGroupController> controller_keepalive(
controller_.get());
scoped_refptr<Endpoint> keepalive(this);
base::AutoLock locker(controller_->lock_);
bool more_to_process = false;
if (!sync_messages_.empty()) {
MessageWrapper message_wrapper =
std::move(sync_messages_.front().second);
sync_messages_.pop_front();
bool dispatch_succeeded;
mojo::InterfaceEndpointClient* client = client_;
{
base::AutoUnlock unlocker(controller_->lock_);
dispatch_succeeded =
client->HandleIncomingMessage(&message_wrapper.value());
}
if (!sync_messages_.empty())
more_to_process = true;
if (!dispatch_succeeded)
controller_->RaiseError();
}
if (!more_to_process)
sync_watcher_->ResetEvent();
// If there are no queued sync messages and the peer has closed, there
// there won't be incoming sync messages in the future. If any
// SyncWatch() calls are on the stack for this endpoint, resetting the
// watcher will allow them to exit as the stack undwinds.
if (!more_to_process && peer_closed_)
sync_watcher_.reset();
}
void EnsureSyncWatcherExists() {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (sync_watcher_)
return;
base::AutoLock locker(controller_->lock_);
sync_watcher_ = std::make_unique<mojo::SequenceLocalSyncEventWatcher>(
base::BindRepeating(&Endpoint::OnSyncMessageEventReady,
base::Unretained(this)));
if (peer_closed_ || !sync_messages_.empty())
SignalSyncMessageEvent();
}
uint32_t GenerateSyncMessageId() {
// Overflow is fine.
uint32_t id = next_sync_message_id_++;
DCHECK(sync_messages_.empty() || sync_messages_.front().first != id);
return id;
}
// Tracks the state of a pending sync wait which excludes all other incoming
// IPC on the waiting thread.
struct ExclusiveSyncWait {
explicit ExclusiveSyncWait(uint64_t request_id)
: request_id(request_id) {}
~ExclusiveSyncWait() = default;
bool TryFulfillingWith(MessageWrapper& wrapper) {
if (!wrapper.HasRequestId(request_id)) {
return false;
}
message = std::move(wrapper);
event.Signal();
return true;
}
uint64_t request_id;
base::WaitableEvent event;
MessageWrapper message;
};
const raw_ptr<ChannelAssociatedGroupController> controller_;
const mojo::InterfaceId id_;
bool closed_ = false;
bool peer_closed_ = false;
bool handle_created_ = false;
bool was_bound_off_sequence_ = false;
std::optional<mojo::DisconnectReason> disconnect_reason_;
raw_ptr<mojo::InterfaceEndpointClient> client_ = nullptr;
scoped_refptr<base::SequencedTaskRunner> task_runner_;
std::unique_ptr<mojo::SequenceLocalSyncEventWatcher> sync_watcher_;
base::circular_deque<std::pair<uint32_t, MessageWrapper>> sync_messages_;
raw_ptr<ExclusiveSyncWait> exclusive_wait_ = nullptr;
uint32_t next_sync_message_id_ = 0;
};
class ControlMessageProxyThunk : public MessageReceiver {
public:
explicit ControlMessageProxyThunk(
ChannelAssociatedGroupController* controller)
: controller_(controller) {}
ControlMessageProxyThunk(const ControlMessageProxyThunk&) = delete;
ControlMessageProxyThunk& operator=(const ControlMessageProxyThunk&) =
delete;
private:
// MessageReceiver:
bool Accept(mojo::Message* message) override {
return controller_->SendMessage(message);
}
raw_ptr<ChannelAssociatedGroupController> controller_;
};
~ChannelAssociatedGroupController() override {
DCHECK(!connector_);
base::AutoLock locker(lock_);
for (auto iter = endpoints_.begin(); iter != endpoints_.end();) {
Endpoint* endpoint = iter->second.get();
++iter;
if (!endpoint->closed()) {
// This happens when a NotifyPeerEndpointClosed message been received,
// but the interface ID hasn't been used to create local endpoint
// handle.
DCHECK(!endpoint->client());
DCHECK(endpoint->peer_closed());
MarkClosed(endpoint);
} else {
MarkPeerClosed(endpoint);
}
}
endpoints_.clear();
GetMemoryDumpProvider().RemoveController(this);
}
bool SendMessage(mojo::Message* message) {
DCHECK(message->heap_profiler_tag());
if (task_runner_->BelongsToCurrentThread()) {
return SendMessageOnSequence(message);
}
// PostTask (or RunOrPostTask) so that `message` is sent after messages from
// tasks that are already queued (e.g. by `IPC::ChannelProxy::Send`).
auto callback = base::BindOnce(
&ChannelAssociatedGroupController::SendMessageOnSequenceViaTask, this,
std::move(*message));
if (base::FeatureList::IsEnabled(
kMojoChannelAssociatedSendUsesRunOrPostTask)) {
task_runner_->RunOrPostTask(base::subtle::RunOrPostTaskPassKey(),
FROM_HERE, std::move(callback));
} else {
task_runner_->PostTask(FROM_HERE, std::move(callback));
}
return true;
}
bool SendMessageOnSequence(mojo::Message* message) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
was_bound_or_message_sent_ = true;
if (!connector_ || paused_) {
if (!shut_down_) {
base::AutoLock lock(outgoing_messages_lock_);
outgoing_messages_.emplace_back(std::move(*message));
}
return true;
}
MojoResult result = connector_->AcceptAndGetResult(message);
if (result == MOJO_RESULT_OK) {
return true;
}
CHECK(connector_->encountered_error(), base::NotFatalUntil::M135);
return false;
}
void SendMessageOnSequenceViaTask(mojo::Message message) {
if (!SendMessageOnSequence(&message)) {
RaiseError();
}
}
void OnPipeError() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// We keep |this| alive here because it's possible for the notifications
// below to release all other references.
scoped_refptr<ChannelAssociatedGroupController> keepalive(this);
base::AutoLock locker(lock_);
encountered_error_ = true;
std::vector<uint32_t> endpoints_to_remove;
std::vector<scoped_refptr<Endpoint>> endpoints_to_notify;
for (auto iter = endpoints_.begin(); iter != endpoints_.end();) {
Endpoint* endpoint = iter->second.get();
++iter;
if (endpoint->client()) {
endpoints_to_notify.push_back(endpoint);
}
if (MarkPeerClosed(endpoint)) {
endpoints_to_remove.push_back(endpoint->id());
}
}
for (auto& endpoint : endpoints_to_notify) {
// Because a notification may in turn detach any endpoint, we have to
// check each client again here.
if (endpoint->client())
NotifyEndpointOfError(endpoint.get(), false /* force_async */);
}
for (uint32_t id : endpoints_to_remove) {
endpoints_.erase(id);
}
}
void NotifyEndpointOfError(Endpoint* endpoint, bool force_async)
EXCLUSIVE_LOCKS_REQUIRED(lock_) {
DCHECK(endpoint->task_runner() && endpoint->client());
if (endpoint->task_runner()->RunsTasksInCurrentSequence() && !force_async) {
mojo::InterfaceEndpointClient* client = endpoint->client();
std::optional<mojo::DisconnectReason> reason(
endpoint->disconnect_reason());
base::AutoUnlock unlocker(lock_);
client->NotifyError(reason);
} else {
endpoint->task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&ChannelAssociatedGroupController::
NotifyEndpointOfErrorOnEndpointThread,
this, endpoint->id(),
// This is safe as `endpoint` is verified to be in
// `endpoints_` (a map with ownership) before use.
base::UnsafeDangling(endpoint)));
}
}
// `endpoint` might be a dangling ptr and must be checked before dereference.
void NotifyEndpointOfErrorOnEndpointThread(mojo::InterfaceId id,
MayBeDangling<Endpoint> endpoint) {
base::AutoLock locker(lock_);
auto iter = endpoints_.find(id);
if (iter == endpoints_.end() || iter->second.get() != endpoint)
return;
if (!endpoint->client())