File: serial_apitest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (412 lines) | stat: -rw-r--r-- 14,051 bytes parent folder | download | duplicates (3)
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
// 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 <map>
#include <memory>
#include <string>
#include <utility>

#include "base/containers/extend.h"
#include "base/containers/span.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/notimplemented.h"
#include "base/unguessable_token.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_test.h"
#include "extensions/browser/api/serial/serial_api.h"
#include "extensions/browser/api/serial/serial_connection.h"
#include "extensions/browser/api/serial/serial_port_manager.h"
#include "extensions/browser/extension_function.h"
#include "extensions/browser/extension_function_registry.h"
#include "extensions/common/api/serial.h"
#include "extensions/common/switches.h"
#include "extensions/test/result_catcher.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "services/device/public/mojom/serial.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"

// Disable SIMULATE_SERIAL_PORTS only if all the following are true:
//
// 1. You have an Arduino or compatible board attached to your machine and
// properly appearing as the first virtual serial port ("first" is very loosely
// defined as whichever port shows up in serial.getPorts). We've tested only
// the Atmega32u4 Breakout Board and Arduino Leonardo; note that both these
// boards are based on the Atmel ATmega32u4, rather than the more common
// Arduino '328p with either FTDI or '8/16u2 USB interfaces. TODO: test more
// widely.
//
// 2. Your user has permission to read/write the port. For example, this might
// mean that your user is in the "tty" or "uucp" group on Ubuntu flavors of
// Linux, or else that the port's path (e.g., /dev/ttyACM0) has global
// read/write permissions.
//
// 3. You have uploaded a program to the board that does a byte-for-byte echo
// on the virtual serial port at 57600 bps. An example is at
// chrome/test/data/extensions/api_test/serial/api/serial_arduino_test.ino.
//
#define SIMULATE_SERIAL_PORTS (1)

using testing::_;
using testing::Return;

namespace extensions {
namespace {

class FakeSerialPort : public device::mojom::SerialPort {
 public:
  explicit FakeSerialPort(device::mojom::SerialPortInfoPtr info)
      : info_(std::move(info)),
        in_stream_watcher_(FROM_HERE,
                           mojo::SimpleWatcher::ArmingPolicy::MANUAL),
        out_stream_watcher_(FROM_HERE,
                            mojo::SimpleWatcher::ArmingPolicy::MANUAL) {
    options_.bitrate = 9600;
    options_.data_bits = device::mojom::SerialDataBits::EIGHT;
    options_.parity_bit = device::mojom::SerialParityBit::NO_PARITY;
    options_.stop_bits = device::mojom::SerialStopBits::ONE;
    options_.cts_flow_control = false;
    options_.has_cts_flow_control = true;
  }

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

  ~FakeSerialPort() override = default;

  mojo::PendingRemote<device::mojom::SerialPort> Open(
      device::mojom::SerialConnectionOptionsPtr options,
      mojo::PendingRemote<device::mojom::SerialPortClient> client) {
    if (receiver_.is_bound()) {
      // Port is already open.
      return mojo::NullRemote();
    }

    DCHECK(!client_.is_bound());
    DCHECK(client.is_valid());
    client_.Bind(std::move(client));

    DoConfigurePort(*options);

    return receiver_.BindNewPipeAndPassRemote();
  }

  const device::mojom::SerialPortInfo& info() { return *info_; }

 private:
  // device::mojom::SerialPort methods:
  void StartWriting(mojo::ScopedDataPipeConsumerHandle consumer) override {
    if (in_stream_) {
      return;
    }

    in_stream_ = std::move(consumer);
    in_stream_watcher_.Watch(
        in_stream_.get(),
        MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
        MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
        base::BindRepeating(&FakeSerialPort::DoWrite, base::Unretained(this)));
    in_stream_watcher_.ArmOrNotify();
  }

  void StartReading(mojo::ScopedDataPipeProducerHandle producer) override {
    if (out_stream_) {
      return;
    }

    out_stream_ = std::move(producer);
    out_stream_watcher_.Watch(
        out_stream_.get(),
        MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
        MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
        base::BindRepeating(&FakeSerialPort::DoRead, base::Unretained(this)));
    out_stream_watcher_.ArmOrNotify();
  }

  void Flush(device::mojom::SerialPortFlushMode mode,
             FlushCallback callback) override {
    if (mode == device::mojom::SerialPortFlushMode::kReceiveAndTransmit) {
      std::move(callback).Run();
      return;
    }

    NOTREACHED();
  }

  void Drain(DrainCallback callback) override { NOTREACHED(); }

  void GetControlSignals(GetControlSignalsCallback callback) override {
    auto signals = device::mojom::SerialPortControlSignals::New();
    signals->dcd = true;
    signals->cts = true;
    signals->ri = true;
    signals->dsr = true;
    std::move(callback).Run(std::move(signals));
  }
  void SetControlSignals(device::mojom::SerialHostControlSignalsPtr signals,
                         SetControlSignalsCallback callback) override {
    std::move(callback).Run(true);
  }
  void ConfigurePort(device::mojom::SerialConnectionOptionsPtr options,
                     ConfigurePortCallback callback) override {
    DoConfigurePort(*options);
    std::move(callback).Run(true);
  }
  void GetPortInfo(GetPortInfoCallback callback) override {
    auto info = device::mojom::SerialConnectionInfo::New();
    info->bitrate = options_.bitrate;
    info->data_bits = options_.data_bits;
    info->parity_bit = options_.parity_bit;
    info->stop_bits = options_.stop_bits;
    info->cts_flow_control = options_.cts_flow_control;
    std::move(callback).Run(std::move(info));
  }

  void Close(bool flush, CloseCallback callback) override {
    in_stream_watcher_.Cancel();
    in_stream_.reset();
    out_stream_watcher_.Cancel();
    out_stream_.reset();
    client_.reset();
    std::move(callback).Run();
    receiver_.reset();
  }

  void DoWrite(MojoResult result, const mojo::HandleSignalsState& state) {
    base::span<const uint8_t> data;
    if (result == MOJO_RESULT_OK) {
      result = in_stream_->BeginReadData(MOJO_READ_DATA_FLAG_NONE, data);
    }
    if (result == MOJO_RESULT_OK) {
      // Control the bytes read from in_stream_ to trigger a variaty of
      // transfer cases between SerialConnection::send_pipe_.
      write_step_++;
      if ((write_step_ % 4) < 2 && data.size() > 1) {
        data = data.first(1u);
      }
      base::Extend(buffer_, data);
      in_stream_->EndReadData(data.size());
      in_stream_watcher_.ArmOrNotify();

      // Enable the notification to write this data to the out stream.
      out_stream_watcher_.ArmOrNotify();
      return;
    }
    if (result == MOJO_RESULT_SHOULD_WAIT) {
      // If there is no space to write, wait for more space.
      in_stream_watcher_.ArmOrNotify();
      return;
    }
    if (result == MOJO_RESULT_FAILED_PRECONDITION ||
        result == MOJO_RESULT_CANCELLED) {
      // The |in_stream_| has been closed.
      in_stream_.reset();
      return;
    }
    // The code should not reach other cases.
    NOTREACHED();
  }

  void DoRead(MojoResult result, const mojo::HandleSignalsState& state) {
    if (result != MOJO_RESULT_OK) {
      out_stream_.reset();
      return;
    }
    if (buffer_.empty()) {
      return;
    }
    read_step_++;
    if (read_step_ == 1) {
      // Write one byte first.
      WriteOutReadData(1);
    } else if (read_step_ == 2) {
      // Write one byte in second step and trigger a break error.
      WriteOutReadData(1);
      DCHECK(client_);
      client_->OnReadError(device::mojom::SerialReceiveError::PARITY_ERROR);
      out_stream_watcher_.Cancel();
      out_stream_.reset();
      return;
    } else {
      // Write out the rest data after reconnecting.
      WriteOutReadData(buffer_.size());
    }
    out_stream_watcher_.ArmOrNotify();
  }

  void WriteOutReadData(size_t num_bytes) {
    base::span<const uint8_t> bytes = buffer_;
    bytes = bytes.first(num_bytes);

    size_t actually_written_bytes = 0;
    MojoResult result = out_stream_->WriteData(bytes, MOJO_WRITE_DATA_FLAG_NONE,
                                               actually_written_bytes);
    if (result == MOJO_RESULT_OK) {
      buffer_.erase(buffer_.begin(), buffer_.begin() + actually_written_bytes);
    }
  }

  void DoConfigurePort(const device::mojom::SerialConnectionOptions& options) {
    // Merge options.
    if (options.bitrate) {
      options_.bitrate = options.bitrate;
    }
    if (options.data_bits != device::mojom::SerialDataBits::NONE) {
      options_.data_bits = options.data_bits;
    }
    if (options.parity_bit != device::mojom::SerialParityBit::NONE) {
      options_.parity_bit = options.parity_bit;
    }
    if (options.stop_bits != device::mojom::SerialStopBits::NONE) {
      options_.stop_bits = options.stop_bits;
    }
    if (options.has_cts_flow_control) {
      DCHECK(options_.has_cts_flow_control);
      options_.cts_flow_control = options.cts_flow_control;
    }
  }

  device::mojom::SerialPortInfoPtr info_;
  mojo::Receiver<device::mojom::SerialPort> receiver_{this};

  // Currently applied connection options.
  device::mojom::SerialConnectionOptions options_;
  std::vector<uint8_t> buffer_;
  int read_step_ = 0;
  int write_step_ = 0;
  mojo::Remote<device::mojom::SerialPortClient> client_;
  mojo::ScopedDataPipeConsumerHandle in_stream_;
  mojo::SimpleWatcher in_stream_watcher_;
  mojo::ScopedDataPipeProducerHandle out_stream_;
  mojo::SimpleWatcher out_stream_watcher_;
};

class FakeSerialPortManager : public device::mojom::SerialPortManager {
 public:
  FakeSerialPortManager() {
    AddPort(base::FilePath(FILE_PATH_LITERAL("/dev/fakeserialmojo")));
    AddPort(base::FilePath(FILE_PATH_LITERAL("\\\\COM800\\")));
  }

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

  ~FakeSerialPortManager() override = default;

  void Bind(mojo::PendingReceiver<device::mojom::SerialPortManager> receiver) {
    receivers_.Add(this, std::move(receiver));
  }

 private:
  // device::mojom::SerialPortManager methods:
  void SetClient(mojo::PendingRemote<device::mojom::SerialPortManagerClient>
                     remote) override {
    NOTIMPLEMENTED();
  }

  void GetDevices(GetDevicesCallback callback) override {
    std::vector<device::mojom::SerialPortInfoPtr> ports;
    for (const auto& port : ports_)
      ports.push_back(port.second->info().Clone());
    std::move(callback).Run(std::move(ports));
  }

  void OpenPort(
      const base::UnguessableToken& token,
      bool use_alternate_path,
      device::mojom::SerialConnectionOptionsPtr options,
      mojo::PendingRemote<device::mojom::SerialPortClient> client,
      mojo::PendingRemote<device::mojom::SerialPortConnectionWatcher> watcher,
      OpenPortCallback callback) override {
    DCHECK(!watcher);
    auto it = ports_.find(token);
    CHECK(it != ports_.end());
    std::move(callback).Run(
        it->second->Open(std::move(options), std::move(client)));
  }

  void AddPort(const base::FilePath& path) {
    auto token = base::UnguessableToken::Create();
    auto port = device::mojom::SerialPortInfo::New();
    port->token = token;
    port->path = path;
    ports_.insert(std::make_pair(
        token, std::make_unique<FakeSerialPort>(std::move(port))));
  }

  mojo::ReceiverSet<device::mojom::SerialPortManager> receivers_;
  std::map<base::UnguessableToken, std::unique_ptr<FakeSerialPort>> ports_;
};

class SerialApiTest : public ExtensionApiTest {
 public:
  SerialApiTest() {
#if SIMULATE_SERIAL_PORTS
    api::SerialPortManager::OverrideBinderForTesting(base::BindRepeating(
        &SerialApiTest::BindSerialPortManager, base::Unretained(this)));
#endif
  }

  ~SerialApiTest() override {
#if SIMULATE_SERIAL_PORTS
    api::SerialPortManager::OverrideBinderForTesting(base::NullCallback());
#endif
  }

  void SetUpOnMainThread() override {
    ExtensionApiTest::SetUpOnMainThread();
    port_manager_ = std::make_unique<FakeSerialPortManager>();
  }

  void FailEnumeratorRequest() { fail_enumerator_request_ = true; }

 protected:
  void BindSerialPortManager(
      mojo::PendingReceiver<device::mojom::SerialPortManager> receiver) {
    if (fail_enumerator_request_)
      return;

    port_manager_->Bind(std::move(receiver));
  }

  bool fail_enumerator_request_ = false;
  std::unique_ptr<FakeSerialPortManager> port_manager_;
};

}  // namespace

IN_PROC_BROWSER_TEST_F(SerialApiTest, SerialFakeHardware) {
  ResultCatcher catcher;
  catcher.RestrictToBrowserContext(browser()->profile());

  ASSERT_TRUE(RunExtensionTest("serial/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(SerialApiTest, SerialRealHardware) {
  ResultCatcher catcher;
  catcher.RestrictToBrowserContext(browser()->profile());

  ASSERT_TRUE(RunExtensionTest("serial/real_hardware")) << message_;
}

IN_PROC_BROWSER_TEST_F(SerialApiTest, SerialRealHardwareFail) {
  ResultCatcher catcher;
  catcher.RestrictToBrowserContext(browser()->profile());

  // chrome.serial.getDevices() should get an empty list when the serial
  // enumerator interface is unavailable.
  FailEnumeratorRequest();
  ASSERT_TRUE(RunExtensionTest("serial/real_hardware_fail")) << message_;
}

}  // namespace extensions