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
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
 1176
 1177
 1178
 1179
 1180
 1181
 1182
 1183
 1184

mojo / core / message_unittest.cc [blame]

// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include <memory>
#include <string_view>
#include <utility>
#include <vector>

#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/numerics/safe_math.h"
#include "base/rand_util.h"
#include "base/ranges/algorithm.h"
#include "build/blink_buildflags.h"
#include "build/build_config.h"
#include "mojo/core/embedder/embedder.h"
#include "mojo/core/ipcz_driver/mojo_message.h"
#include "mojo/core/test/mojo_test_base.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/system/buffer.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "mojo/public/cpp/system/platform_handle.h"

#if BUILDFLAG(MOJO_SUPPORT_LEGACY_CORE)
#include "mojo/core/user_message_impl.h"
#endif

namespace mojo::core {
namespace {

using MessageTest = test::MojoTestBase;

#if BUILDFLAG(MOJO_SUPPORT_LEGACY_CORE)
constexpr uint32_t kLegacyMinimumPayloadBufferSize = kMinimumPayloadBufferSize;
#else
constexpr uint32_t kLegacyMinimumPayloadBufferSize = 0;
#endif

// Helper class which provides a base implementation for an unserialized user
// message context and helpers to go between these objects and opaque message
// handles.
class TestMessageBase {
 public:
  virtual ~TestMessageBase() = default;

  static MojoMessageHandle MakeMessageHandle(
      std::unique_ptr<TestMessageBase> message) {
    MojoMessageHandle handle;
    MojoResult rv = MojoCreateMessage(nullptr, &handle);
    DCHECK_EQ(MOJO_RESULT_OK, rv);

    rv = MojoSetMessageContext(
        handle, reinterpret_cast<uintptr_t>(message.release()),
        &TestMessageBase::SerializeMessageContext,
        &TestMessageBase::DestroyMessageContext, nullptr);
    DCHECK_EQ(MOJO_RESULT_OK, rv);

    return handle;
  }

  template <typename T>
  static std::unique_ptr<T> UnwrapMessageHandle(
      MojoMessageHandle* message_handle) {
    MojoMessageHandle handle = MOJO_HANDLE_INVALID;
    std::swap(handle, *message_handle);
    uintptr_t context;
    MojoResult rv = MojoGetMessageContext(handle, nullptr, &context);
    DCHECK_EQ(MOJO_RESULT_OK, rv);
    rv = MojoSetMessageContext(handle, 0, nullptr, nullptr, nullptr);
    DCHECK_EQ(MOJO_RESULT_OK, rv);
    MojoDestroyMessage(handle);
    return base::WrapUnique(reinterpret_cast<T*>(context));
  }

 protected:
  virtual void GetSerializedSize(size_t* num_bytes, size_t* num_handles) = 0;
  virtual void SerializeHandles(MojoHandle* handles) = 0;
  virtual void SerializePayload(void* buffer) = 0;

 private:
  static void SerializeMessageContext(MojoMessageHandle message_handle,
                                      uintptr_t context) {
    auto* message = reinterpret_cast<TestMessageBase*>(context);
    size_t num_bytes = 0;
    size_t num_handles = 0;
    message->GetSerializedSize(&num_bytes, &num_handles);
    std::vector<MojoHandle> handles(num_handles);
    if (num_handles)
      message->SerializeHandles(handles.data());

    MojoAppendMessageDataOptions options;
    options.struct_size = sizeof(options);
    options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
    void* buffer;
    uint32_t buffer_size;
    MojoResult rv = MojoAppendMessageData(
        message_handle, base::checked_cast<uint32_t>(num_bytes), handles.data(),
        base::checked_cast<uint32_t>(num_handles), &options, &buffer,
        &buffer_size);
    DCHECK_EQ(MOJO_RESULT_OK, rv);
    DCHECK_GE(buffer_size, base::checked_cast<uint32_t>(num_bytes));
    if (num_bytes)
      message->SerializePayload(buffer);
  }

  static void DestroyMessageContext(uintptr_t context) {
    delete reinterpret_cast<TestMessageBase*>(context);
  }
};

class NeverSerializedMessage : public TestMessageBase {
 public:
  NeverSerializedMessage(
      base::OnceClosure destruction_callback = base::OnceClosure())
      : destruction_callback_(std::move(destruction_callback)) {}

  NeverSerializedMessage(const NeverSerializedMessage&) = delete;
  NeverSerializedMessage& operator=(const NeverSerializedMessage&) = delete;

  ~NeverSerializedMessage() override {
    if (destruction_callback_)
      std::move(destruction_callback_).Run();
  }

 private:
  // TestMessageBase:
  void GetSerializedSize(size_t* num_bytes, size_t* num_handles) override {
    NOTREACHED();
  }
  void SerializeHandles(MojoHandle* handles) override { NOTREACHED(); }
  void SerializePayload(void* buffer) override { NOTREACHED(); }

  base::OnceClosure destruction_callback_;
};

class SimpleMessage : public TestMessageBase {
 public:
  SimpleMessage(const std::string& contents,
                base::OnceClosure destruction_callback = base::OnceClosure())
      : contents_(contents),
        destruction_callback_(std::move(destruction_callback)) {}

  SimpleMessage(const SimpleMessage&) = delete;
  SimpleMessage& operator=(const SimpleMessage&) = delete;

  ~SimpleMessage() override {
    if (destruction_callback_)
      std::move(destruction_callback_).Run();
  }

  void AddMessagePipe(mojo::ScopedMessagePipeHandle handle) {
    handles_.emplace_back(std::move(handle));
  }

  std::vector<mojo::ScopedMessagePipeHandle>& handles() { return handles_; }

 private:
  // TestMessageBase:
  void GetSerializedSize(size_t* num_bytes, size_t* num_handles) override {
    *num_bytes = contents_.size();
    *num_handles = handles_.size();
  }

  void SerializeHandles(MojoHandle* handles) override {
    ASSERT_TRUE(!handles_.empty());
    for (size_t i = 0; i < handles_.size(); ++i)
      handles[i] = handles_[i].release().value();
    handles_.clear();
  }

  void SerializePayload(void* buffer) override {
    base::ranges::copy(contents_, static_cast<char*>(buffer));
  }

  const std::string contents_;
  base::OnceClosure destruction_callback_;
  std::vector<mojo::ScopedMessagePipeHandle> handles_;
};

TEST_F(MessageTest, InvalidMessageObjects) {
  ASSERT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            MojoDestroyMessage(MOJO_MESSAGE_HANDLE_INVALID));

  ASSERT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            MojoAppendMessageData(MOJO_MESSAGE_HANDLE_INVALID, 0, nullptr, 0,
                                  nullptr, nullptr, nullptr));

  ASSERT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            MojoGetMessageData(MOJO_MESSAGE_HANDLE_INVALID, nullptr, nullptr,
                               nullptr, nullptr, nullptr));

  ASSERT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            MojoSerializeMessage(MOJO_MESSAGE_HANDLE_INVALID, nullptr));

  MojoMessageHandle message_handle;
  ASSERT_EQ(MOJO_RESULT_INVALID_ARGUMENT, MojoCreateMessage(nullptr, nullptr));
  ASSERT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message_handle));
  ASSERT_EQ(MOJO_RESULT_OK, MojoSetMessageContext(message_handle, 0, nullptr,
                                                  nullptr, nullptr));
  ASSERT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));
}

TEST_F(MessageTest, SendLocalMessageWithContext) {
  // Simple write+read of a message with context. Verifies that such messages
  // are passed through a local pipe without serialization.
  auto message = std::make_unique<NeverSerializedMessage>();
  auto* original_message = message.get();

  MojoHandle a, b;
  CreateMessagePipe(&a, &b);
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoWriteMessage(
          a, TestMessageBase::MakeMessageHandle(std::move(message)), nullptr));
  EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(b, MOJO_HANDLE_SIGNAL_READABLE));

  MojoMessageHandle read_message_handle;
  EXPECT_EQ(MOJO_RESULT_OK, MojoReadMessage(b, nullptr, &read_message_handle));
  message = TestMessageBase::UnwrapMessageHandle<NeverSerializedMessage>(
      &read_message_handle);
  EXPECT_EQ(original_message, message.get());

  MojoClose(a);
  MojoClose(b);
}

TEST_F(MessageTest, DestroyMessageWithContext) {
  // Tests that |MojoDestroyMessage()| destroys any attached context.
  bool was_deleted = false;
  auto message = std::make_unique<NeverSerializedMessage>(base::BindOnce(
      [](bool* was_deleted) { *was_deleted = true; }, &was_deleted));
  MojoMessageHandle handle =
      TestMessageBase::MakeMessageHandle(std::move(message));
  EXPECT_FALSE(was_deleted);
  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(handle));
  EXPECT_TRUE(was_deleted);
}

const char kTestMessageWithContext1[] = "hello laziness";

#if BUILDFLAG(USE_BLINK)

const char kTestMessageWithContext2[] = "my old friend";
const char kTestMessageWithContext3[] = "something something";
const char kTestMessageWithContext4[] = "do moar ipc";
const char kTestQuitMessage[] = "quit";

DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReceiveMessageNoHandles, MessageTest, h) {
  MojoTestBase::WaitForSignals(h, MOJO_HANDLE_SIGNAL_READABLE);
  auto m = MojoTestBase::ReadMessage(h);
  EXPECT_EQ(kTestMessageWithContext1, m);
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h));
}

#if BUILDFLAG(IS_IOS)
// TODO(crbug.com/40257752): Test currently fails on iOS.
#define MAYBE_SerializeSimpleMessageNoHandlesWithContext \
  DISABLED_SerializeSimpleMessageNoHandlesWithContext
#else
#define MAYBE_SerializeSimpleMessageNoHandlesWithContext \
  SerializeSimpleMessageNoHandlesWithContext
#endif  // BUILDFLAG(IS_IOS)
TEST_F(MessageTest, MAYBE_SerializeSimpleMessageNoHandlesWithContext) {
  RunTestClient("ReceiveMessageNoHandles", [&](MojoHandle h) {
    auto message = std::make_unique<SimpleMessage>(kTestMessageWithContext1);
    MojoWriteMessage(h, TestMessageBase::MakeMessageHandle(std::move(message)),
                     nullptr);
  });
}

#if BUILDFLAG(IS_IOS)
// TODO(crbug.com/40257752): Test currently fails on iOS.
#define MAYBE_SerializeDynamicallySizedMessage \
  DISABLED_SerializeDynamicallySizedMessage
#else
#define MAYBE_SerializeDynamicallySizedMessage SerializeDynamicallySizedMessage
#endif  // BUILDFLAG(IS_IOS)
TEST_F(MessageTest, MAYBE_SerializeDynamicallySizedMessage) {
  RunTestClient("ReceiveMessageNoHandles", [&](MojoHandle h) {
    MojoMessageHandle message;
    EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));

    void* buffer;
    uint32_t buffer_size;
    EXPECT_EQ(MOJO_RESULT_OK,
              MojoAppendMessageData(message, 0, nullptr, 0, nullptr, &buffer,
                                    &buffer_size));

    MojoAppendMessageDataOptions options;
    options.struct_size = sizeof(options);
    options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
    EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(
                                  message, sizeof(kTestMessageWithContext1) - 1,
                                  nullptr, 0, &options, &buffer, &buffer_size));

    memcpy(buffer, kTestMessageWithContext1,
           sizeof(kTestMessageWithContext1) - 1);
    MojoWriteMessage(h, message, nullptr);
  });
}

DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReceiveMessageOneHandle, MessageTest, h) {
  MojoTestBase::WaitForSignals(h, MOJO_HANDLE_SIGNAL_READABLE);
  MojoHandle h1;
  auto m = MojoTestBase::ReadMessageWithHandles(h, &h1, 1);
  EXPECT_EQ(kTestMessageWithContext1, m);
  MojoTestBase::WriteMessage(h1, kTestMessageWithContext2);
  EXPECT_EQ(kTestQuitMessage, MojoTestBase::ReadMessage(h));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h1));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h));
}

#if BUILDFLAG(IS_IOS)
// TODO(crbug.com/40257752): Test currently fails on iOS.
#define MAYBE_SerializeSimpleMessageOneHandleWithContext \
  DISABLED_SerializeSimpleMessageOneHandleWithContext
#else
#define MAYBE_SerializeSimpleMessageOneHandleWithContext \
  SerializeSimpleMessageOneHandleWithContext
#endif  // BUILDFLAG(IS_IOS)
TEST_F(MessageTest, MAYBE_SerializeSimpleMessageOneHandleWithContext) {
  RunTestClient("ReceiveMessageOneHandle", [&](MojoHandle h) {
    auto message = std::make_unique<SimpleMessage>(kTestMessageWithContext1);
    mojo::MessagePipe pipe;
    message->AddMessagePipe(std::move(pipe.handle0));
    MojoWriteMessage(h, TestMessageBase::MakeMessageHandle(std::move(message)),
                     nullptr);
    EXPECT_EQ(kTestMessageWithContext2,
              MojoTestBase::ReadMessage(pipe.handle1.get().value()));
    MojoTestBase::WriteMessage(h, kTestQuitMessage);
  });
}

DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReceiveMessageWithHandles, MessageTest, h) {
  MojoTestBase::WaitForSignals(h, MOJO_HANDLE_SIGNAL_READABLE);
  MojoHandle handles[4];
  auto m = MojoTestBase::ReadMessageWithHandles(h, handles, 4);
  EXPECT_EQ(kTestMessageWithContext1, m);
  MojoTestBase::WriteMessage(handles[0], kTestMessageWithContext1);
  MojoTestBase::WriteMessage(handles[1], kTestMessageWithContext2);
  MojoTestBase::WriteMessage(handles[2], kTestMessageWithContext3);
  MojoTestBase::WriteMessage(handles[3], kTestMessageWithContext4);

  EXPECT_EQ(kTestQuitMessage, MojoTestBase::ReadMessage(h));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[0]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[1]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[2]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[3]));
}

#if BUILDFLAG(IS_IOS)
// TODO(crbug.com/40257752): Test currently fails on iOS.
#define MAYBE_SerializeSimpleMessageWithHandlesWithContext \
  DISABLED_SerializeSimpleMessageWithHandlesWithContext
#else
#define MAYBE_SerializeSimpleMessageWithHandlesWithContext \
  SerializeSimpleMessageWithHandlesWithContext
#endif  // BUILDFLAG(IS_IOS)
TEST_F(MessageTest, MAYBE_SerializeSimpleMessageWithHandlesWithContext) {
  RunTestClient("ReceiveMessageWithHandles", [&](MojoHandle h) {
    auto message = std::make_unique<SimpleMessage>(kTestMessageWithContext1);
    mojo::MessagePipe pipes[4];
    message->AddMessagePipe(std::move(pipes[0].handle0));
    message->AddMessagePipe(std::move(pipes[1].handle0));
    message->AddMessagePipe(std::move(pipes[2].handle0));
    message->AddMessagePipe(std::move(pipes[3].handle0));
    MojoWriteMessage(h, TestMessageBase::MakeMessageHandle(std::move(message)),
                     nullptr);
    EXPECT_EQ(kTestMessageWithContext1,
              MojoTestBase::ReadMessage(pipes[0].handle1.get().value()));
    EXPECT_EQ(kTestMessageWithContext2,
              MojoTestBase::ReadMessage(pipes[1].handle1.get().value()));
    EXPECT_EQ(kTestMessageWithContext3,
              MojoTestBase::ReadMessage(pipes[2].handle1.get().value()));
    EXPECT_EQ(kTestMessageWithContext4,
              MojoTestBase::ReadMessage(pipes[3].handle1.get().value()));

    MojoTestBase::WriteMessage(h, kTestQuitMessage);
  });
}

#endif  // BUILDFLAG(USE_BLINK)

TEST_F(MessageTest, SendLocalSimpleMessageWithHandlesWithContext) {
  auto message = std::make_unique<SimpleMessage>(kTestMessageWithContext1);
  auto* original_message = message.get();
  mojo::MessagePipe pipes[4];
  MojoHandle original_handles[4] = {
      pipes[0].handle0.get().value(), pipes[1].handle0.get().value(),
      pipes[2].handle0.get().value(), pipes[3].handle0.get().value(),
  };
  message->AddMessagePipe(std::move(pipes[0].handle0));
  message->AddMessagePipe(std::move(pipes[1].handle0));
  message->AddMessagePipe(std::move(pipes[2].handle0));
  message->AddMessagePipe(std::move(pipes[3].handle0));

  MojoHandle a, b;
  CreateMessagePipe(&a, &b);
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoWriteMessage(
          a, TestMessageBase::MakeMessageHandle(std::move(message)), nullptr));
  EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(b, MOJO_HANDLE_SIGNAL_READABLE));

  MojoMessageHandle read_message_handle;
  EXPECT_EQ(MOJO_RESULT_OK, MojoReadMessage(b, nullptr, &read_message_handle));
  message =
      TestMessageBase::UnwrapMessageHandle<SimpleMessage>(&read_message_handle);
  EXPECT_EQ(original_message, message.get());
  ASSERT_EQ(4u, message->handles().size());
  EXPECT_EQ(original_handles[0], message->handles()[0].get().value());
  EXPECT_EQ(original_handles[1], message->handles()[1].get().value());
  EXPECT_EQ(original_handles[2], message->handles()[2].get().value());
  EXPECT_EQ(original_handles[3], message->handles()[3].get().value());

  MojoClose(a);
  MojoClose(b);
}

TEST_F(MessageTest, DropUnreadLocalMessageWithContext) {
  // Verifies that if a message is sent with context over a pipe and the
  // receiver closes without reading the message, the context is properly
  // cleaned up.
  bool message_was_destroyed = false;
  auto message = std::make_unique<SimpleMessage>(
      kTestMessageWithContext1,
      base::BindOnce([](bool* was_destroyed) { *was_destroyed = true; },
                     &message_was_destroyed));

  mojo::MessagePipe pipe;
  message->AddMessagePipe(std::move(pipe.handle0));
  MojoHandle a, b;
  CreateMessagePipe(&a, &b);
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoWriteMessage(
          a, TestMessageBase::MakeMessageHandle(std::move(message)), nullptr));
  MojoClose(a);
  MojoClose(b);

  EXPECT_TRUE(message_was_destroyed);
  EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(pipe.handle1.get().value(),
                                           MOJO_HANDLE_SIGNAL_PEER_CLOSED));
}

TEST_F(MessageTest, GetMessageDataWithHandles) {
  MojoHandle h[2];
  CreateMessagePipe(&h[0], &h[1]);

  MojoMessageHandle message_handle;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message_handle));

  MojoAppendMessageDataOptions append_data_options;
  append_data_options.struct_size = sizeof(append_data_options);
  append_data_options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  const std::string kTestMessage = "hello";
  void* buffer;
  uint32_t buffer_size;
  ASSERT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(
                message_handle, static_cast<uint32_t>(kTestMessage.size()), h,
                2, &append_data_options, &buffer, &buffer_size));
  memcpy(buffer, kTestMessage.data(), kTestMessage.size());

  // Ignore handles the first time around. This should mean a subsequent call is
  // allowed to grab the handles.
  MojoGetMessageDataOptions get_data_options;
  get_data_options.struct_size = sizeof(get_data_options);
  get_data_options.flags = MOJO_GET_MESSAGE_DATA_FLAG_IGNORE_HANDLES;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoGetMessageData(message_handle, &get_data_options, &buffer,
                               &buffer_size, nullptr, nullptr));

  // Now grab the handles.
  uint32_t num_handles = 2;
  EXPECT_EQ(MOJO_RESULT_OK, MojoGetMessageData(message_handle, nullptr, &buffer,
                                               &buffer_size, h, &num_handles));
  EXPECT_EQ(2u, num_handles);

  // Should still be callable as long as we ignore handles.
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoGetMessageData(message_handle, &get_data_options, &buffer,
                               &buffer_size, nullptr, nullptr));

  // But not if we don't.
  EXPECT_EQ(MOJO_RESULT_NOT_FOUND,
            MojoGetMessageData(message_handle, nullptr, &buffer, &buffer_size,
                               h, &num_handles));

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h[0]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h[1]));
}

TEST_F(MessageTest, ReadMessageWithContextAsSerializedMessage) {
  bool message_was_destroyed = false;
  std::unique_ptr<TestMessageBase> message =
      std::make_unique<NeverSerializedMessage>(
          base::BindOnce([](bool* was_destroyed) { *was_destroyed = true; },
                         &message_was_destroyed));

  MojoHandle a, b;
  CreateMessagePipe(&a, &b);
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoWriteMessage(
          a, TestMessageBase::MakeMessageHandle(std::move(message)), nullptr));
  EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(b, MOJO_HANDLE_SIGNAL_READABLE));

  MojoMessageHandle message_handle;
  EXPECT_EQ(MOJO_RESULT_OK, MojoReadMessage(b, nullptr, &message_handle));
  EXPECT_FALSE(message_was_destroyed);

  // Not a serialized message, so we can't get serialized contents.
  uint32_t num_bytes = 0;
  void* buffer;
  uint32_t num_handles = 0;
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
            MojoGetMessageData(message_handle, nullptr, &buffer, &num_bytes,
                               nullptr, &num_handles));
  EXPECT_FALSE(message_was_destroyed);

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));
  EXPECT_TRUE(message_was_destroyed);

  MojoClose(a);
  MojoClose(b);
}

TEST_F(MessageTest, ReadSerializedMessageAsMessageWithContext) {
  MojoHandle a, b;
  CreateMessagePipe(&a, &b);
  MojoTestBase::WriteMessage(a, "hello there");
  EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(b, MOJO_HANDLE_SIGNAL_READABLE));

  MojoMessageHandle message_handle;
  EXPECT_EQ(MOJO_RESULT_OK, MojoReadMessage(b, nullptr, &message_handle));
  uintptr_t context;
  EXPECT_EQ(MOJO_RESULT_NOT_FOUND,
            MojoGetMessageContext(message_handle, nullptr, &context));
  MojoClose(a);
  MojoClose(b);
  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));
}

TEST_F(MessageTest, ForceSerializeMessageWithContext) {
  // Basic test - we can serialize a simple message.
  bool message_was_destroyed = false;
  auto message = std::make_unique<SimpleMessage>(
      kTestMessageWithContext1,
      base::BindOnce([](bool* was_destroyed) { *was_destroyed = true; },
                     &message_was_destroyed));
  auto message_handle = TestMessageBase::MakeMessageHandle(std::move(message));
  EXPECT_EQ(MOJO_RESULT_OK, MojoSerializeMessage(message_handle, nullptr));
  EXPECT_TRUE(message_was_destroyed);
  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));

  // Serialize a message with a single handle. Freeing the message should close
  // the handle.
  message_was_destroyed = false;
  message = std::make_unique<SimpleMessage>(
      kTestMessageWithContext1,
      base::BindOnce([](bool* was_destroyed) { *was_destroyed = true; },
                     &message_was_destroyed));
  MessagePipe pipe1;
  message->AddMessagePipe(std::move(pipe1.handle0));
  message_handle = TestMessageBase::MakeMessageHandle(std::move(message));
  EXPECT_EQ(MOJO_RESULT_OK, MojoSerializeMessage(message_handle, nullptr));
  EXPECT_TRUE(message_was_destroyed);
  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));
  EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(pipe1.handle1.get().value(),
                                           MOJO_HANDLE_SIGNAL_PEER_CLOSED));

  // Serialize a message with a handle and extract its serialized contents.
  message_was_destroyed = false;
  message = std::make_unique<SimpleMessage>(
      kTestMessageWithContext1,
      base::BindOnce([](bool* was_destroyed) { *was_destroyed = true; },
                     &message_was_destroyed));
  MessagePipe pipe2;
  message->AddMessagePipe(std::move(pipe2.handle0));
  message_handle = TestMessageBase::MakeMessageHandle(std::move(message));
  EXPECT_EQ(MOJO_RESULT_OK, MojoSerializeMessage(message_handle, nullptr));
  EXPECT_TRUE(message_was_destroyed);
  uint32_t num_bytes = 0;
  void* buffer = nullptr;
  uint32_t num_handles = 0;
  MojoHandle extracted_handle;
  EXPECT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
            MojoGetMessageData(message_handle, nullptr, &buffer, &num_bytes,
                               nullptr, &num_handles));
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoGetMessageData(message_handle, nullptr, &buffer, &num_bytes,
                               &extracted_handle, &num_handles));
  EXPECT_EQ(std::string(kTestMessageWithContext1).size(), num_bytes);
  EXPECT_EQ(std::string(kTestMessageWithContext1),
            std::string_view(static_cast<char*>(buffer), num_bytes));

  // Confirm that the handle we extracted from the serialized message is still
  // connected to the same peer, despite the fact that its handle value may have
  // changed.
  const char kTestMessage[] = "hey you";
  MojoTestBase::WriteMessage(pipe2.handle1.get().value(), kTestMessage);
  EXPECT_EQ(MOJO_RESULT_OK,
            WaitForSignals(extracted_handle, MOJO_HANDLE_SIGNAL_READABLE));
  EXPECT_EQ(kTestMessage, MojoTestBase::ReadMessage(extracted_handle));

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(extracted_handle));
}

TEST_F(MessageTest, DoubleSerialize) {
  bool message_was_destroyed = false;
  auto message = std::make_unique<SimpleMessage>(
      kTestMessageWithContext1,
      base::BindOnce([](bool* was_destroyed) { *was_destroyed = true; },
                     &message_was_destroyed));
  auto message_handle = TestMessageBase::MakeMessageHandle(std::move(message));

  // Ensure we can safely call |MojoSerializeMessage()| twice on the same
  // message handle.
  EXPECT_EQ(MOJO_RESULT_OK, MojoSerializeMessage(message_handle, nullptr));
  EXPECT_TRUE(message_was_destroyed);
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
            MojoSerializeMessage(message_handle, nullptr));

  // And also check that we can call it again after we've written and read the
  // message object from a pipe.
  MessagePipe pipe;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoWriteMessage(pipe.handle0->value(), message_handle, nullptr));
  EXPECT_EQ(MOJO_RESULT_OK,
            WaitForSignals(pipe.handle1->value(), MOJO_HANDLE_SIGNAL_READABLE));
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoReadMessage(pipe.handle1->value(), nullptr, &message_handle));
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
            MojoSerializeMessage(message_handle, nullptr));

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message_handle));
}

TEST_F(MessageTest, ExtendMessagePayload) {
  MojoMessageHandle message;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));

  const std::string kTestMessagePart1("hello i am message.");
  void* buffer;
  uint32_t buffer_size;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(
                message, static_cast<uint32_t>(kTestMessagePart1.size()),
                nullptr, 0, nullptr, &buffer, &buffer_size));
  ASSERT_GE(buffer_size, static_cast<uint32_t>(kTestMessagePart1.size()));
  memcpy(buffer, kTestMessagePart1.data(), kTestMessagePart1.size());

  const std::string kTestMessagePart2 = " in ur computer.";
  const std::string kTestMessageCombined1 =
      kTestMessagePart1 + kTestMessagePart2;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(
                message, static_cast<uint32_t>(kTestMessagePart2.size()),
                nullptr, 0, nullptr, &buffer, &buffer_size));
  memcpy(static_cast<uint8_t*>(buffer) + kTestMessagePart1.size(),
         kTestMessagePart2.data(), kTestMessagePart2.size());

  const std::string kTestMessagePart3 = kTestMessagePart2 + " carry ur bits.";
  const std::string kTestMessageCombined2 =
      kTestMessageCombined1 + kTestMessagePart3;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(
                message, static_cast<uint32_t>(kTestMessagePart3.size()),
                nullptr, 0, nullptr, &buffer, &buffer_size));
  memcpy(static_cast<uint8_t*>(buffer) + kTestMessageCombined1.size(),
         kTestMessagePart3.data(), kTestMessagePart3.size());

  void* payload;
  uint32_t payload_size;
  EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION,
            MojoGetMessageData(message, nullptr, &payload, &payload_size,
                               nullptr, nullptr));

  MojoAppendMessageDataOptions options;
  options.struct_size = sizeof(options);
  options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, nullptr, 0,
                                                  &options, nullptr, nullptr));

  EXPECT_EQ(MOJO_RESULT_OK,
            MojoGetMessageData(message, nullptr, &payload, &payload_size,
                               nullptr, nullptr));
  EXPECT_EQ(kTestMessageCombined2.size(), payload_size);
  EXPECT_EQ(0, memcmp(payload, kTestMessageCombined2.data(),
                      kTestMessageCombined2.size()));

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
}

TEST_F(MessageTest, PreallocateEnoughMemoryForMessage) {
  MojoMessageHandle message;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));

  // We need to calculate our payload sizes based on `kMinimumBufferSize` here,
  // because if we use a total payload size smaller than that, the buffer may
  // not be reallocated when we expect it to (since at least
  // `kMinimumBufferSize` bytes of capacity will be allocated).
  const size_t kMinimumBufferSize =
      IsMojoIpczEnabled() ? ipcz_driver::MojoMessage::kMinBufferSize
                          : kLegacyMinimumPayloadBufferSize;
  const std::string kMsgPart1(kMinimumBufferSize / 2, 'x');
  const std::string kMsgPart2(kMinimumBufferSize, 'y');
  const std::string kCombined = kMsgPart1 + kMsgPart2;
  // Overestimate the amount of memory required. 16 is picked as it should
  // be larger than adjustments due to memory alignment.
  const size_t estimated_size = kCombined.size() + 16;

  // Preallocate `estimated_size`, enough for `kCombined`.
  uint32_t buffer_size;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoReserveMessageCapacity(
                message, static_cast<uint32_t>(estimated_size), &buffer_size));
  EXPECT_GE(buffer_size, static_cast<uint32_t>(estimated_size));
  uint32_t prev_buffer_size = buffer_size;

  // Append `kMsgPart1`.
  void* buffer;
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoAppendMessageData(message, static_cast<uint32_t>(kMsgPart1.size()),
                            nullptr, 0, nullptr, &buffer, &buffer_size));
  memcpy(buffer, kMsgPart1.data(), kMsgPart1.size());
  // No reallocation expected since enough capacity should be reserved.
  EXPECT_EQ(buffer_size, prev_buffer_size);
  void* prev_buffer = buffer;

  // Append `kMsgPart2`.
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoAppendMessageData(message, static_cast<uint32_t>(kMsgPart2.size()),
                            nullptr, 0, nullptr, &buffer, &buffer_size));
  memcpy(static_cast<uint8_t*>(buffer) + kMsgPart1.size(), kMsgPart2.data(),
         kMsgPart2.size());
  // No reallocation expected since enough capacity should be reserved.
  EXPECT_EQ(buffer, prev_buffer);
  EXPECT_EQ(buffer_size, prev_buffer_size);

  // Finalize message by committing the final size.
  MojoAppendMessageDataOptions options;
  options.struct_size = sizeof(options);
  options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, nullptr, 0,
                                                  &options, nullptr, nullptr));

  // Check payload content and size.
  void* payload;
  uint32_t payload_size;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoGetMessageData(message, nullptr, &payload, &payload_size,
                               nullptr, nullptr));
  EXPECT_GE(estimated_size, payload_size);
  EXPECT_EQ(kCombined.size(), payload_size);
  EXPECT_EQ(0, memcmp(payload, kCombined.data(), kCombined.size()));

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
}

TEST_F(MessageTest, PreallocateNotEnoughMemoryForMessage) {
  MojoMessageHandle message;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));

  // We need to calculate our payload sizes based on `kMinimumBufferSize` here,
  // because if we use a total payload size smaller than that, the buffer may
  // not be reallocated when we expect it to (since at least
  // `kMinimumBufferSize` bytes of capacity will be allocated).
  const size_t kMinimumBufferSize =
      IsMojoIpczEnabled() ? ipcz_driver::MojoMessage::kMinBufferSize
                          : kLegacyMinimumPayloadBufferSize;
  const std::string kMsgPart1(kMinimumBufferSize / 2, 'x');
  const std::string kMsgPart2(kMinimumBufferSize, 'y');
  const std::string kCombined = kMsgPart1 + kMsgPart2;
  // Underestimate the amount of memory required. 16 is picked as it should
  // be larger than adjustments due to memory alignment.
  const size_t estimated_size = kCombined.size() - 16;

  // Preallocate `estimated_size`, not enough for `kCombined`.
  uint32_t buffer_size;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoReserveMessageCapacity(
                message, static_cast<uint32_t>(estimated_size), &buffer_size));
  EXPECT_GE(buffer_size, static_cast<uint32_t>(estimated_size));
  uint32_t prev_buffer_size = buffer_size;

  // Append `kMsgPart1`.
  void* buffer;
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoAppendMessageData(message, static_cast<uint32_t>(kMsgPart1.size()),
                            nullptr, 0, nullptr, &buffer, &buffer_size));
  memcpy(buffer, kMsgPart1.data(), kMsgPart1.size());
  // No reallocation expected since enough capacity should be reserved.
  EXPECT_EQ(buffer_size, prev_buffer_size);

  // Append `kMsgPart2`.
  EXPECT_EQ(
      MOJO_RESULT_OK,
      MojoAppendMessageData(message, static_cast<uint32_t>(kMsgPart2.size()),
                            nullptr, 0, nullptr, &buffer, &buffer_size));
  memcpy(static_cast<uint8_t*>(buffer) + kMsgPart1.size(), kMsgPart2.data(),
         kMsgPart2.size());
  // Since the preallocated size was intentionally underestimated, this
  // should reallocate and grow the buffer.
  EXPECT_GT(buffer_size, prev_buffer_size);
  EXPECT_GT(buffer_size, static_cast<uint32_t>(estimated_size));

  // Finalize message by committing the final size.
  MojoAppendMessageDataOptions options;
  options.struct_size = sizeof(options);
  options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, nullptr, 0,
                                                  &options, nullptr, nullptr));

  // Check payload content and size.
  void* payload;
  uint32_t payload_size;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoGetMessageData(message, nullptr, &payload, &payload_size,
                               nullptr, nullptr));
  EXPECT_LT(estimated_size, payload_size);
  EXPECT_EQ(kCombined.size(), payload_size);
  EXPECT_EQ(0, memcmp(payload, kCombined.data(), kCombined.size()));

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
}

TEST_F(MessageTest, ExtendMessageWithHandlesPayload) {
  MojoMessageHandle message;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));

  MojoHandle handles[2];
  CreateMessagePipe(&handles[0], &handles[1]);

  const std::string kTestMessagePart1("hello i am message.");
  void* buffer;
  uint32_t buffer_size;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(
                message, static_cast<uint32_t>(kTestMessagePart1.size()),
                handles, 2, nullptr, &buffer, &buffer_size));
  ASSERT_GE(buffer_size, static_cast<uint32_t>(kTestMessagePart1.size()));
  memcpy(buffer, kTestMessagePart1.data(), kTestMessagePart1.size());

  const std::string kTestMessagePart2 = " in ur computer.";
  const std::string kTestMessageCombined1 =
      kTestMessagePart1 + kTestMessagePart2;
  MojoAppendMessageDataOptions options;
  options.struct_size = sizeof(options);
  options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(
                message, static_cast<uint32_t>(kTestMessagePart2.size()),
                nullptr, 0, &options, &buffer, &buffer_size));
  memcpy(static_cast<uint8_t*>(buffer) + kTestMessagePart1.size(),
         kTestMessagePart2.data(), kTestMessagePart2.size());

  void* payload;
  uint32_t payload_size;
  uint32_t num_handles = 2;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoGetMessageData(message, nullptr, &payload, &payload_size,
                               handles, &num_handles));
  EXPECT_EQ(2u, num_handles);
  EXPECT_EQ(kTestMessageCombined1.size(), payload_size);
  EXPECT_EQ(0, memcmp(payload, kTestMessageCombined1.data(),
                      kTestMessageCombined1.size()));

  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[0]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[1]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
}

TEST_F(MessageTest, ExtendMessagePayloadLarge) {
  // We progressively extend a message payload from small to large using various
  // chunk sizes to test potentially interesting boundary conditions.
  constexpr size_t kTestChunkSizes[] = {1, 2, 3, 64, 509, 4096, 16384, 65535};
  for (const size_t kChunkSize : kTestChunkSizes) {
    MojoMessageHandle message;
    EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));

    MojoHandle handles[2];
    CreateMessagePipe(&handles[0], &handles[1]);

    const std::string kTestMessageHeader("hey pretend i'm a header");
    void* buffer;
    uint32_t buffer_size;
    EXPECT_EQ(MOJO_RESULT_OK,
              MojoAppendMessageData(
                  message, static_cast<uint32_t>(kTestMessageHeader.size()),
                  handles, 2, nullptr, &buffer, &buffer_size));
    ASSERT_GE(buffer_size, static_cast<uint32_t>(kTestMessageHeader.size()));
    memcpy(buffer, kTestMessageHeader.data(), kTestMessageHeader.size());

    // 512 kB should be well beyond any reasonable default buffer size for the
    // system implementation to choose, meaning that this test should guarantee
    // several reallocations of the serialized message buffer as we
    // progressively extend the payload to this size.
    constexpr size_t kTestMessagePayloadSize = 512 * 1024;
    std::vector<uint8_t> test_payload(kTestMessagePayloadSize);
    base::RandBytes(test_payload);

    size_t current_payload_size = 0;
    while (current_payload_size < kTestMessagePayloadSize) {
      const size_t previous_payload_size = current_payload_size;
      current_payload_size =
          std::min(current_payload_size + kChunkSize, kTestMessagePayloadSize);
      const size_t current_chunk_size =
          current_payload_size - previous_payload_size;
      const size_t previous_total_size =
          kTestMessageHeader.size() + previous_payload_size;
      const size_t current_total_size =
          kTestMessageHeader.size() + current_payload_size;
      EXPECT_EQ(MOJO_RESULT_OK,
                MojoAppendMessageData(
                    message, static_cast<uint32_t>(current_chunk_size), nullptr,
                    0, nullptr, &buffer, &buffer_size));
      EXPECT_GE(buffer_size, static_cast<uint32_t>(current_total_size));
      memcpy(static_cast<uint8_t*>(buffer) + previous_total_size,
             &test_payload[previous_payload_size], current_chunk_size);
    }

    MojoAppendMessageDataOptions options;
    options.struct_size = sizeof(options);
    options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
    EXPECT_EQ(MOJO_RESULT_OK,
              MojoAppendMessageData(message, 0, nullptr, 0, &options, nullptr,
                                    nullptr));

    void* payload;
    uint32_t payload_size;
    uint32_t num_handles = 2;
    EXPECT_EQ(MOJO_RESULT_OK,
              MojoGetMessageData(message, nullptr, &payload, &payload_size,
                                 handles, &num_handles));
    EXPECT_EQ(static_cast<uint32_t>(kTestMessageHeader.size() +
                                    kTestMessagePayloadSize),
              payload_size);
    EXPECT_EQ(0, memcmp(payload, kTestMessageHeader.data(),
                        kTestMessageHeader.size()));
    EXPECT_EQ(0,
              memcmp(static_cast<uint8_t*>(payload) + kTestMessageHeader.size(),
                     test_payload.data(), kTestMessagePayloadSize));

    EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[0]));
    EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[1]));
    EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
  }
}

TEST_F(MessageTest, CorrectPayloadBufferBoundaries) {
  // Exercises writes to the full extent of a message's payload under various
  // circumstances in an effort to catch any potential bugs in internal
  // allocations or reported size from Mojo APIs.

  MojoMessageHandle message;
  void* buffer = nullptr;
  uint32_t buffer_size = 0;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(message, 0, nullptr, 0, nullptr, &buffer,
                                  &buffer_size));
  // Fill the buffer end-to-end.
  memset(buffer, 'x', buffer_size);

  // Continuously grow and fill the message buffer several more times. Should
  // not crash.
  constexpr uint32_t kChunkSize = 4096;
  constexpr size_t kNumIterations = 1000;
  for (size_t i = 0; i < kNumIterations; ++i) {
    EXPECT_EQ(MOJO_RESULT_OK,
              MojoAppendMessageData(message, kChunkSize, nullptr, 0, nullptr,
                                    &buffer, &buffer_size));
    memset(buffer, 'x', buffer_size);
  }

  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
}

#if BUILDFLAG(MOJO_SUPPORT_LEGACY_CORE)
TEST_F(MessageTest, CommitInvalidMessageContents) {
  // Regression test for https://crbug.com/755127. Ensures that we don't crash
  // if we attempt to commit the contents of an unserialized message.
  MojoMessageHandle message;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, nullptr, 0,
                                                  nullptr, nullptr, nullptr));
  MojoHandle a, b;
  CreateMessagePipe(&a, &b);
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, &a, 1, nullptr,
                                                  nullptr, nullptr));

  UserMessageImpl::FailHandleSerializationForTesting(true);
  MojoAppendMessageDataOptions options;
  options.struct_size = sizeof(options);
  options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, nullptr, 0,
                                                  nullptr, nullptr, nullptr));
  UserMessageImpl::FailHandleSerializationForTesting(false);
  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(b));
}
#endif  // BUILDFLAG(MOJO_SUPPORT_LEGACY_CORE)

#if BUILDFLAG(USE_BLINK)

#if BUILDFLAG(IS_IOS)
// TODO(crbug.com/40257752): Test currently fails on iOS.
#define MAYBE_ExtendPayloadWithHandlesAttached \
  DISABLED_ExtendPayloadWithHandlesAttached
#else
#define MAYBE_ExtendPayloadWithHandlesAttached ExtendPayloadWithHandlesAttached
#endif  // BUILDFLAG(IS_IOS)
TEST_F(MessageTest, MAYBE_ExtendPayloadWithHandlesAttached) {
  // Regression test for https://crbug.com/748996. Verifies that internal
  // message objects do not retain invalid payload pointers across buffer
  // relocations.

  MojoHandle handles[5];
  CreateMessagePipe(&handles[0], &handles[1]);
  PlatformChannel channel;
  handles[2] =
      WrapPlatformHandle(channel.TakeLocalEndpoint().TakePlatformHandle())
          .release()
          .value();
  handles[3] =
      WrapPlatformHandle(channel.TakeRemoteEndpoint().TakePlatformHandle())
          .release()
          .value();
  handles[4] = SharedBufferHandle::Create(64).release().value();

  MojoMessageHandle message;
  void* buffer = nullptr;
  uint32_t buffer_size = 0;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(message, 0, handles, 5, nullptr, &buffer,
                                  &buffer_size));

  // Force buffer reallocation by extending the payload beyond the original
  // buffer size. This should typically result in a relocation of the buffer as
  // well -- at least often enough that breakage will be caught by automated
  // tests.
  MojoAppendMessageDataOptions options;
  options.struct_size = sizeof(options);
  options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  uint32_t payload_size = buffer_size * 64;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(message, payload_size, nullptr, 0, &options,
                                  &buffer, &buffer_size));
  ASSERT_GE(buffer_size, payload_size);
  memset(buffer, 'x', payload_size);

  RunTestClient("ReadAndIgnoreMessage", [&](MojoHandle h) {
    // Send the message out of process to exercise the regression path where
    // internally cached, stale payload pointers may be dereferenced and written
    // into.
    EXPECT_EQ(MOJO_RESULT_OK, MojoWriteMessage(h, message, nullptr));
  });
}

DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReadAndIgnoreMessage, MessageTest, h) {
  MojoTestBase::WaitForSignals(h, MOJO_HANDLE_SIGNAL_READABLE);

  MojoHandle handles[5];
  MojoTestBase::ReadMessageWithHandles(h, handles, 5);
  for (size_t i = 0; i < 5; ++i)
    EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[i]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h));
}

#if BUILDFLAG(IS_IOS)
// TODO(crbug.com/40257752): Test currently fails on iOS.
#define MAYBE_ExtendPayloadWithHandlesAttachedViaExtension \
  DISABLED_ExtendPayloadWithHandlesAttachedViaExtension
#else
#define MAYBE_ExtendPayloadWithHandlesAttachedViaExtension \
  ExtendPayloadWithHandlesAttachedViaExtension
#endif  // BUILDFLAG(IS_IOS)
TEST_F(MessageTest, MAYBE_ExtendPayloadWithHandlesAttachedViaExtension) {
  MojoHandle handles[5];
  CreateMessagePipe(&handles[0], &handles[4]);
  PlatformChannel channel;
  handles[1] =
      WrapPlatformHandle(channel.TakeLocalEndpoint().TakePlatformHandle())
          .release()
          .value();
  handles[2] =
      WrapPlatformHandle(channel.TakeRemoteEndpoint().TakePlatformHandle())
          .release()
          .value();
  handles[3] = SharedBufferHandle::Create(64).release().value();

  MojoMessageHandle message;
  void* buffer = nullptr;
  uint32_t buffer_size = 0;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(message, 0, handles, 1, nullptr, &buffer,
                                  &buffer_size));
  uint32_t payload_size = buffer_size * 64;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(message, payload_size, nullptr, 0, nullptr,
                                  &buffer, nullptr));

  // Add more handles.
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, handles + 1, 1,
                                                  nullptr, &buffer, nullptr));
  MojoAppendMessageDataOptions options;
  options.struct_size = sizeof(options);
  options.flags = MOJO_APPEND_MESSAGE_DATA_FLAG_COMMIT_SIZE;
  EXPECT_EQ(MOJO_RESULT_OK, MojoAppendMessageData(message, 0, handles + 2, 3,
                                                  &options, &buffer, nullptr));
  memset(buffer, 'x', payload_size);

  RunTestClient("ReadMessageAndCheckPipe", [&](MojoHandle h) {
    // Send the message out of process to exercise the regression path where
    // internally cached, stale payload pointers may be dereferenced and written
    // into.
    EXPECT_EQ(MOJO_RESULT_OK, MojoWriteMessage(h, message, nullptr));
  });
}

DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReadMessageAndCheckPipe, MessageTest, h) {
  MojoTestBase::WaitForSignals(h, MOJO_HANDLE_SIGNAL_READABLE);

  const std::string kTestMessage("hey pipe");
  MojoHandle handles[5];
  MojoTestBase::ReadMessageWithHandles(h, handles, 5);
  MojoTestBase::WriteMessage(handles[0], kTestMessage);
  MojoTestBase::WaitForSignals(handles[4], MOJO_HANDLE_SIGNAL_READABLE);
  EXPECT_EQ(kTestMessage, MojoTestBase::ReadMessage(handles[4]));
  for (size_t i = 0; i < 5; ++i)
    EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[i]));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(h));
}

#endif  // BUILDFLAG(USE_BLINK)

TEST_F(MessageTest, PartiallySerializedMessagesDontLeakHandles) {
  MojoMessageHandle message;
  EXPECT_EQ(MOJO_RESULT_OK, MojoCreateMessage(nullptr, &message));

  MojoHandle handles[2];
  CreateMessagePipe(&handles[0], &handles[1]);

  const std::string kTestMessagePart1("hello i am message.");
  void* buffer;
  uint32_t buffer_size;
  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(
                message, static_cast<uint32_t>(kTestMessagePart1.size()),
                nullptr, 0, nullptr, &buffer, &buffer_size));
  ASSERT_GE(buffer_size, static_cast<uint32_t>(kTestMessagePart1.size()));
  memcpy(buffer, kTestMessagePart1.data(), kTestMessagePart1.size());

  EXPECT_EQ(MOJO_RESULT_OK,
            MojoAppendMessageData(message, 0, handles, 1, nullptr, &buffer,
                                  &buffer_size));

  // This must close |handles[0]|, which we can detect by observing the
  // signal state of |handles[1].
  EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
  EXPECT_EQ(MOJO_RESULT_OK,
            WaitForSignals(handles[1], MOJO_HANDLE_SIGNAL_PEER_CLOSED));
  EXPECT_EQ(MOJO_RESULT_OK, MojoClose(handles[1]));
}

}  // namespace
}  // namespace mojo::core