1// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
2// for details. All rights reserved. Use of this source code is governed by a
3// BSD-style license that can be found in the LICENSE file.
4
5#ifndef RUNTIME_VM_PORT_H_
6#define RUNTIME_VM_PORT_H_
7
8#include <memory>
9
10#include "include/dart_api.h"
11#include "vm/allocation.h"
12#include "vm/globals.h"
13#include "vm/json_stream.h"
14#include "vm/port_set.h"
15#include "vm/random.h"
16
17namespace dart {
18
19class Isolate;
20class Message;
21class MessageHandler;
22class Mutex;
23class PortMapTestPeer;
24
25class PortMap : public AllStatic {
26 public:
27 enum PortState {
28 kNewPort = 0, // a newly allocated port
29 kLivePort = 1, // a regular port (has a ReceivePort)
30 kControlPort = 2, // a special control port (has a ReceivePort)
31 };
32
33 // Allocate a port for the provided handler and return its VM-global id.
34 static Dart_Port CreatePort(MessageHandler* handler);
35
36 // Indicates that a port has had a ReceivePort created for it at the
37 // dart language level. The port remains live until it is closed.
38 static void SetPortState(Dart_Port id, PortState kind);
39
40 // Close the port with id. All pending messages will be dropped.
41 //
42 // Returns true if the port is successfully closed.
43 static bool ClosePort(Dart_Port id);
44
45 // Close all the ports for the provided handler.
46 static void ClosePorts(MessageHandler* handler);
47
48 // Enqueues the message in the port with id. Returns false if the port is not
49 // active any longer.
50 //
51 // Claims ownership of 'message'.
52 static bool PostMessage(std::unique_ptr<Message> message,
53 bool before_events = false);
54
55 // Returns whether a port is local to the current isolate.
56 static bool IsLocalPort(Dart_Port id);
57
58 // Returns the owning Isolate for port 'id'.
59 static Isolate* GetIsolate(Dart_Port id);
60
61 static bool IsReceiverInThisIsolateGroup(Dart_Port receiver,
62 IsolateGroup* group);
63
64 static void Init();
65 static void Cleanup();
66
67 static void PrintPortsForMessageHandler(MessageHandler* handler,
68 JSONStream* stream);
69
70 static void DebugDumpForMessageHandler(MessageHandler* handler);
71
72 private:
73 friend class dart::PortMapTestPeer;
74
75 struct Entry : public PortSet<Entry>::Entry {
76 Entry() : handler(nullptr), state(kNewPort) {}
77
78 MessageHandler* handler;
79 PortState state;
80 };
81
82 static const char* PortStateString(PortState state);
83
84 // Allocate a new unique port.
85 static Dart_Port AllocatePort();
86
87 static bool IsActivePort(Dart_Port id);
88 static bool IsLivePort(Dart_Port id);
89
90 // Lock protecting access to the port map.
91 static Mutex* mutex_;
92
93 static PortSet<Entry>* ports_;
94 static MessageHandler* deleted_entry_;
95
96 static Random* prng_;
97};
98
99} // namespace dart
100
101#endif // RUNTIME_VM_PORT_H_
102