| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2012, 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 library _isolate_helper; | |
| 6 | |
| 7 import 'dart:_js_embedded_names' show | |
| 8 CLASS_ID_EXTRACTOR, | |
| 9 CLASS_FIELDS_EXTRACTOR, | |
| 10 CREATE_NEW_ISOLATE, | |
| 11 CURRENT_SCRIPT, | |
| 12 GLOBAL_FUNCTIONS, | |
| 13 INITIALIZE_EMPTY_INSTANCE, | |
| 14 INSTANCE_FROM_CLASS_ID; | |
| 15 | |
| 16 import 'dart:async'; | |
| 17 import 'dart:collection' show Queue; | |
| 18 import 'dart:isolate'; | |
| 19 import 'dart:_native_typed_data' show NativeByteBuffer, NativeTypedData; | |
| 20 | |
| 21 import 'dart:_js_helper' show | |
| 22 Closure, | |
| 23 InternalMap, | |
| 24 Null, | |
| 25 Primitives, | |
| 26 convertDartClosureToJS, | |
| 27 isDartObject, | |
| 28 random64, | |
| 29 requiresPreamble; | |
| 30 | |
| 31 import 'dart:_foreign_helper' show DART_CLOSURE_TO_JS, | |
| 32 JS, | |
| 33 JS_CURRENT_ISOLATE_CONTEXT, | |
| 34 JS_CURRENT_ISOLATE, | |
| 35 JS_EMBEDDED_GLOBAL, | |
| 36 JS_SET_CURRENT_ISOLATE, | |
| 37 IsolateContext; | |
| 38 | |
| 39 import 'dart:_interceptors' show Interceptor, | |
| 40 JSArray, | |
| 41 JSExtendableArray, | |
| 42 JSFixedArray, | |
| 43 JSIndexable, | |
| 44 JSMutableArray, | |
| 45 JSObject; | |
| 46 | |
| 47 | |
| 48 part 'isolate_serialization.dart'; | |
| 49 | |
| 50 /** | |
| 51 * Called by the compiler to support switching | |
| 52 * between isolates when we get a callback from the DOM. | |
| 53 */ | |
| 54 _callInIsolate(_IsolateContext isolate, Function function) { | |
| 55 var result = isolate.eval(function); | |
| 56 // If we are not already running the event-loop start it now. | |
| 57 if (!_currentIsolate()._isExecutingEvent) _globalState.topEventLoop.run(); | |
| 58 return result; | |
| 59 } | |
| 60 | |
| 61 /// Marks entering a JavaScript async operation to keep the worker alive. | |
| 62 /// | |
| 63 /// To be called by library code before starting an async operation controlled | |
| 64 /// by the JavaScript event handler. | |
| 65 /// | |
| 66 /// Also call [leaveJsAsync] in all callback handlers marking the end of that | |
| 67 /// async operation (also error handlers) so the worker can be released. | |
| 68 /// | |
| 69 /// These functions only has to be called for code that can be run from a | |
| 70 /// worker-isolate (so not for general dom operations). | |
| 71 enterJsAsync() { | |
| 72 _globalState.topEventLoop._activeJsAsyncCount++; | |
| 73 } | |
| 74 | |
| 75 /// Marks leaving a javascript async operation. | |
| 76 /// | |
| 77 /// See [enterJsAsync]. | |
| 78 leaveJsAsync() { | |
| 79 _globalState.topEventLoop._activeJsAsyncCount--; | |
| 80 assert(_globalState.topEventLoop._activeJsAsyncCount >= 0); | |
| 81 } | |
| 82 | |
| 83 /// Returns true if we are currently in a worker context. | |
| 84 bool isWorker() => _globalState.isWorker; | |
| 85 | |
| 86 /** | |
| 87 * Called by the compiler to fetch the current isolate context. | |
| 88 */ | |
| 89 _IsolateContext _currentIsolate() => _globalState.currentContext; | |
| 90 | |
| 91 /** | |
| 92 * Wrapper that takes the dart entry point and runs it within an isolate. The | |
| 93 * dart2js compiler will inject a call of the form | |
| 94 * [: startRootIsolate(main); :] when it determines that this wrapping | |
| 95 * is needed. For single-isolate applications (e.g. hello world), this | |
| 96 * call is not emitted. | |
| 97 */ | |
| 98 void startRootIsolate(entry, args) { | |
| 99 // The dartMainRunner can inject a new arguments array. We pass the arguments | |
| 100 // through a "JS", so that the type-inferrer loses track of it. | |
| 101 args = JS("", "#", args); | |
| 102 if (args == null) args = []; | |
| 103 if (args is! List) { | |
| 104 throw new ArgumentError("Arguments to main must be a List: $args"); | |
| 105 } | |
| 106 _globalState = new _Manager(entry); | |
| 107 | |
| 108 // Don't start the main loop again, if we are in a worker. | |
| 109 if (_globalState.isWorker) return; | |
| 110 final rootContext = new _IsolateContext(); | |
| 111 _globalState.rootContext = rootContext; | |
| 112 | |
| 113 // BUG(5151491): Setting currentContext should not be necessary, but | |
| 114 // because closures passed to the DOM as event handlers do not bind their | |
| 115 // isolate automatically we try to give them a reasonable context to live in | |
| 116 // by having a "default" isolate (the first one created). | |
| 117 _globalState.currentContext = rootContext; | |
| 118 if (entry is _MainFunctionArgs) { | |
| 119 rootContext.eval(() { entry(args); }); | |
| 120 } else if (entry is _MainFunctionArgsMessage) { | |
| 121 rootContext.eval(() { entry(args, null); }); | |
| 122 } else { | |
| 123 rootContext.eval(entry); | |
| 124 } | |
| 125 _globalState.topEventLoop.run(); | |
| 126 } | |
| 127 | |
| 128 /******************************************************** | |
| 129 Inserted from lib/isolate/dart2js/isolateimpl.dart | |
| 130 ********************************************************/ | |
| 131 | |
| 132 /** | |
| 133 * Concepts used here: | |
| 134 * | |
| 135 * "manager" - A manager contains one or more isolates, schedules their | |
| 136 * execution, and performs other plumbing on their behalf. The isolate | |
| 137 * present at the creation of the manager is designated as its "root isolate". | |
| 138 * A manager may, for example, be implemented on a web Worker. | |
| 139 * | |
| 140 * [_Manager] - State present within a manager (exactly once, as a global). | |
| 141 * | |
| 142 * [_ManagerStub] - A handle held within one manager that allows interaction | |
| 143 * with another manager. A target manager may be addressed by zero or more | |
| 144 * [_ManagerStub]s. | |
| 145 * TODO(ahe): The _ManagerStub concept is broken. It was an attempt | |
| 146 * to create a common interface between the native Worker class and | |
| 147 * _MainManagerStub. | |
| 148 */ | |
| 149 | |
| 150 /** | |
| 151 * A native object that is shared across isolates. This object is visible to all | |
| 152 * isolates running under the same manager (either UI or background web worker). | |
| 153 * | |
| 154 * This is code that is intended to 'escape' the isolate boundaries in order to | |
| 155 * implement the semantics of isolates in JavaScript. Without this we would have | |
| 156 * been forced to implement more code (including the top-level event loop) in | |
| 157 * JavaScript itself. | |
| 158 */ | |
| 159 // TODO(eub, sigmund): move the "manager" to be entirely in JS. | |
| 160 // Running any Dart code outside the context of an isolate gives it | |
| 161 // the chance to break the isolate abstraction. | |
| 162 _Manager get _globalState => JS("_Manager", "init.globalState"); | |
| 163 | |
| 164 set _globalState(_Manager val) { | |
| 165 JS("void", "init.globalState = #", val); | |
| 166 } | |
| 167 | |
| 168 /** State associated with the current manager. See [globalState]. */ | |
| 169 // TODO(sigmund): split in multiple classes: global, thread, main-worker states? | |
| 170 class _Manager { | |
| 171 | |
| 172 /** Next available isolate id within this [_Manager]. */ | |
| 173 int nextIsolateId = 0; | |
| 174 | |
| 175 /** id assigned to this [_Manager]. */ | |
| 176 int currentManagerId = 0; | |
| 177 | |
| 178 /** | |
| 179 * Next available manager id. Only used by the main manager to assign a unique | |
| 180 * id to each manager created by it. | |
| 181 */ | |
| 182 int nextManagerId = 1; | |
| 183 | |
| 184 /** Context for the currently running [Isolate]. */ | |
| 185 _IsolateContext currentContext = null; | |
| 186 | |
| 187 /** Context for the root [Isolate] that first run in this [_Manager]. */ | |
| 188 _IsolateContext rootContext = null; | |
| 189 | |
| 190 /** The top-level event loop. */ | |
| 191 _EventLoop topEventLoop; | |
| 192 | |
| 193 /** Whether this program is running from the command line. */ | |
| 194 bool fromCommandLine; | |
| 195 | |
| 196 /** Whether this [_Manager] is running as a web worker. */ | |
| 197 bool isWorker; | |
| 198 | |
| 199 /** Whether we support spawning web workers. */ | |
| 200 bool supportsWorkers; | |
| 201 | |
| 202 /** | |
| 203 * Whether to use web workers when implementing isolates. Set to false for | |
| 204 * debugging/testing. | |
| 205 */ | |
| 206 bool get useWorkers => supportsWorkers; | |
| 207 | |
| 208 /** | |
| 209 * Registry of isolates. Isolates must be registered if, and only if, receive | |
| 210 * ports are alive. Normally no open receive-ports means that the isolate is | |
| 211 * dead, but DOM callbacks could resurrect it. | |
| 212 */ | |
| 213 Map<int, _IsolateContext> isolates; | |
| 214 | |
| 215 /** Reference to the main [_Manager]. Null in the main [_Manager] itself. */ | |
| 216 _MainManagerStub mainManager; | |
| 217 | |
| 218 /// Registry of active Web Workers. Only used in the main [_Manager]. | |
| 219 Map<int, dynamic /* Worker */> managers; | |
| 220 | |
| 221 /** The entry point given by [startRootIsolate]. */ | |
| 222 final Function entry; | |
| 223 | |
| 224 _Manager(this.entry) { | |
| 225 _nativeDetectEnvironment(); | |
| 226 topEventLoop = new _EventLoop(); | |
| 227 isolates = new Map<int, _IsolateContext>(); | |
| 228 managers = new Map<int, dynamic>(); | |
| 229 if (isWorker) { // "if we are not the main manager ourself" is the intent. | |
| 230 mainManager = new _MainManagerStub(); | |
| 231 _nativeInitWorkerMessageHandler(); | |
| 232 } | |
| 233 } | |
| 234 | |
| 235 void _nativeDetectEnvironment() { | |
| 236 bool isWindowDefined = globalWindow != null; | |
| 237 bool isWorkerDefined = globalWorker != null; | |
| 238 | |
| 239 isWorker = !isWindowDefined && globalPostMessageDefined; | |
| 240 supportsWorkers = isWorker | |
| 241 || (isWorkerDefined && IsolateNatives.thisScript != null); | |
| 242 fromCommandLine = !isWindowDefined && !isWorker; | |
| 243 } | |
| 244 | |
| 245 void _nativeInitWorkerMessageHandler() { | |
| 246 var function = JS('', | |
| 247 "(function (f, a) { return function (e) { f(a, e); }})(#, #)", | |
| 248 DART_CLOSURE_TO_JS(IsolateNatives._processWorkerMessage), | |
| 249 mainManager); | |
| 250 JS("void", r"self.onmessage = #", function); | |
| 251 // We ensure dartPrint is defined so that the implementation of the Dart | |
| 252 // print method knows what to call. | |
| 253 JS('', '''self.dartPrint = self.dartPrint || (function(serialize) { | |
| 254 return function (object) { | |
| 255 if (self.console && self.console.log) { | |
| 256 self.console.log(object) | |
| 257 } else { | |
| 258 self.postMessage(serialize(object)); | |
| 259 } | |
| 260 } | |
| 261 })(#)''', DART_CLOSURE_TO_JS(_serializePrintMessage)); | |
| 262 } | |
| 263 | |
| 264 static _serializePrintMessage(object) { | |
| 265 return _serializeMessage({"command": "print", "msg": object}); | |
| 266 } | |
| 267 | |
| 268 /** | |
| 269 * Close the worker running this code if all isolates are done and | |
| 270 * there are no active async JavaScript tasks still running. | |
| 271 */ | |
| 272 void maybeCloseWorker() { | |
| 273 if (isWorker | |
| 274 && isolates.isEmpty | |
| 275 && topEventLoop._activeJsAsyncCount == 0) { | |
| 276 mainManager.postMessage(_serializeMessage({'command': 'close'})); | |
| 277 } | |
| 278 } | |
| 279 } | |
| 280 | |
| 281 /** Context information tracked for each isolate. */ | |
| 282 class _IsolateContext implements IsolateContext { | |
| 283 /** Current isolate id. */ | |
| 284 final int id = _globalState.nextIsolateId++; | |
| 285 | |
| 286 /** Registry of receive ports currently active on this isolate. */ | |
| 287 final Map<int, RawReceivePortImpl> ports = new Map<int, RawReceivePortImpl>(); | |
| 288 | |
| 289 /** Registry of weak receive ports currently active on this isolate. */ | |
| 290 final Set<int> weakPorts = new Set<int>(); | |
| 291 | |
| 292 /** Holds isolate globals (statics and top-level properties). */ | |
| 293 // native object containing all globals of an isolate. | |
| 294 final isolateStatics = | |
| 295 JS('', "#()", JS_EMBEDDED_GLOBAL('', CREATE_NEW_ISOLATE)); | |
| 296 | |
| 297 final RawReceivePortImpl controlPort = new RawReceivePortImpl._controlPort(); | |
| 298 | |
| 299 final Capability pauseCapability = new Capability(); | |
| 300 final Capability terminateCapability = new Capability(); // License to kill. | |
| 301 | |
| 302 /// Boolean flag set when the initial method of the isolate has been executed. | |
| 303 /// | |
| 304 /// Used to avoid considering the isolate dead when it has no open | |
| 305 /// receive ports and no scheduled timers, because it hasn't had time to | |
| 306 /// create them yet. | |
| 307 bool initialized = false; | |
| 308 | |
| 309 // TODO(lrn): Store these in single "PauseState" object, so they don't take | |
| 310 // up as much room when not pausing. | |
| 311 bool isPaused = false; | |
| 312 List<_IsolateEvent> delayedEvents = []; | |
| 313 Set<Capability> pauseTokens = new Set(); | |
| 314 | |
| 315 // Container with the "on exit" handler send-ports and responses. | |
| 316 var doneHandlers; | |
| 317 | |
| 318 /** | |
| 319 * Queue of functions to call when the current event is complete. | |
| 320 * | |
| 321 * These events are not just put at the front of the event queue, because | |
| 322 * they represent control messages, and should be handled even if the | |
| 323 * event queue is paused. | |
| 324 */ | |
| 325 var _scheduledControlEvents; | |
| 326 bool _isExecutingEvent = false; | |
| 327 | |
| 328 /** Whether uncaught errors are considered fatal. */ | |
| 329 bool errorsAreFatal = true; | |
| 330 | |
| 331 // Set of ports that listen to uncaught errors. | |
| 332 Set<SendPort> errorPorts = new Set(); | |
| 333 | |
| 334 _IsolateContext() { | |
| 335 this.registerWeak(controlPort._id, controlPort); | |
| 336 } | |
| 337 | |
| 338 void addPause(Capability authentification, Capability resume) { | |
| 339 if (pauseCapability != authentification) return; | |
| 340 if (pauseTokens.add(resume) && !isPaused) { | |
| 341 isPaused = true; | |
| 342 } | |
| 343 _updateGlobalState(); | |
| 344 } | |
| 345 | |
| 346 void removePause(Capability resume) { | |
| 347 if (!isPaused) return; | |
| 348 pauseTokens.remove(resume); | |
| 349 if (pauseTokens.isEmpty) { | |
| 350 while(delayedEvents.isNotEmpty) { | |
| 351 _IsolateEvent event = delayedEvents.removeLast(); | |
| 352 _globalState.topEventLoop.prequeue(event); | |
| 353 } | |
| 354 isPaused = false; | |
| 355 } | |
| 356 _updateGlobalState(); | |
| 357 } | |
| 358 | |
| 359 void addDoneListener(SendPort responsePort, Object response) { | |
| 360 if (doneHandlers == null) { | |
| 361 doneHandlers = []; | |
| 362 } | |
| 363 for (int i = 0; i < doneHandlers.length; i += 2) { | |
| 364 if (responsePort == doneHandlers[i]) { | |
| 365 doneHandlers[i + 1] = response; | |
| 366 return; | |
| 367 } | |
| 368 } | |
| 369 doneHandlers.add(responsePort); | |
| 370 doneHandlers.add(response); | |
| 371 } | |
| 372 | |
| 373 void removeDoneListener(SendPort responsePort) { | |
| 374 if (doneHandlers == null) return; | |
| 375 for (int i = 0; i < doneHandlers.length; i += 2) { | |
| 376 if (responsePort == doneHandlers[i]) { | |
| 377 doneHandlers.removeRange(i, i + 2); | |
| 378 return; | |
| 379 } | |
| 380 } | |
| 381 } | |
| 382 | |
| 383 void setErrorsFatal(Capability authentification, bool errorsAreFatal) { | |
| 384 if (terminateCapability != authentification) return; | |
| 385 this.errorsAreFatal = errorsAreFatal; | |
| 386 } | |
| 387 | |
| 388 void handlePing(SendPort responsePort, int pingType, Object response) { | |
| 389 if (pingType == Isolate.IMMEDIATE || | |
| 390 (pingType == Isolate.BEFORE_NEXT_EVENT && | |
| 391 !_isExecutingEvent)) { | |
| 392 responsePort.send(response); | |
| 393 return; | |
| 394 } | |
| 395 void respond() { responsePort.send(response); } | |
| 396 assert(pingType == Isolate.BEFORE_NEXT_EVENT); | |
| 397 if (_scheduledControlEvents == null) { | |
| 398 _scheduledControlEvents = new Queue(); | |
| 399 } | |
| 400 _scheduledControlEvents.addLast(respond); | |
| 401 } | |
| 402 | |
| 403 void handleKill(Capability authentification, int priority) { | |
| 404 if (this.terminateCapability != authentification) return; | |
| 405 if (priority == Isolate.IMMEDIATE || | |
| 406 (priority == Isolate.BEFORE_NEXT_EVENT && | |
| 407 !_isExecutingEvent)) { | |
| 408 kill(); | |
| 409 return; | |
| 410 } | |
| 411 assert(priority == Isolate.BEFORE_NEXT_EVENT); | |
| 412 if (_scheduledControlEvents == null) { | |
| 413 _scheduledControlEvents = new Queue(); | |
| 414 } | |
| 415 _scheduledControlEvents.addLast(kill); | |
| 416 } | |
| 417 | |
| 418 void addErrorListener(SendPort port) { | |
| 419 errorPorts.add(port); | |
| 420 } | |
| 421 | |
| 422 void removeErrorListener(SendPort port) { | |
| 423 errorPorts.remove(port); | |
| 424 } | |
| 425 | |
| 426 /** Function called with an uncaught error. */ | |
| 427 void handleUncaughtError(error, StackTrace stackTrace) { | |
| 428 // Just print the error if there is no error listener registered. | |
| 429 if (errorPorts.isEmpty) { | |
| 430 // An uncaught error in the root isolate will terminate the program? | |
| 431 if (errorsAreFatal && identical(this, _globalState.rootContext)) { | |
| 432 // The error will be rethrown to reach the global scope, so | |
| 433 // don't print it. | |
| 434 return; | |
| 435 } | |
| 436 if (JS('bool', 'self.console && self.console.error')) { | |
| 437 JS('void', 'self.console.error(#, #)', error, stackTrace); | |
| 438 } else { | |
| 439 print(error); | |
| 440 if (stackTrace != null) print(stackTrace); | |
| 441 } | |
| 442 return; | |
| 443 } | |
| 444 List message = new List(2) | |
| 445 ..[0] = error.toString() | |
| 446 ..[1] = (stackTrace == null) ? null : stackTrace.toString(); | |
| 447 for (SendPort port in errorPorts) port.send(message); | |
| 448 } | |
| 449 | |
| 450 /** | |
| 451 * Run [code] in the context of the isolate represented by [this]. | |
| 452 */ | |
| 453 dynamic eval(Function code) { | |
| 454 var old = _globalState.currentContext; | |
| 455 _globalState.currentContext = this; | |
| 456 this._setGlobals(); | |
| 457 var result = null; | |
| 458 var oldIsExecutingEvent = _isExecutingEvent; | |
| 459 _isExecutingEvent = true; | |
| 460 try { | |
| 461 result = code(); | |
| 462 } catch (e, s) { | |
| 463 handleUncaughtError(e, s); | |
| 464 if (errorsAreFatal) { | |
| 465 kill(); | |
| 466 // An uncaught error in the root context terminates all isolates. | |
| 467 if (identical(this, _globalState.rootContext)) { | |
| 468 rethrow; | |
| 469 } | |
| 470 } | |
| 471 } finally { | |
| 472 _isExecutingEvent = oldIsExecutingEvent; | |
| 473 _globalState.currentContext = old; | |
| 474 if (old != null) old._setGlobals(); | |
| 475 if (_scheduledControlEvents != null) { | |
| 476 while (_scheduledControlEvents.isNotEmpty) { | |
| 477 (_scheduledControlEvents.removeFirst())(); | |
| 478 } | |
| 479 } | |
| 480 } | |
| 481 return result; | |
| 482 } | |
| 483 | |
| 484 void _setGlobals() { | |
| 485 JS_SET_CURRENT_ISOLATE(isolateStatics); | |
| 486 } | |
| 487 | |
| 488 /** | |
| 489 * Handle messages comming in on the control port. | |
| 490 * | |
| 491 * These events do not go through the event queue. | |
| 492 * The `_globalState.currentContext` context is not set to this context | |
| 493 * during the handling. | |
| 494 */ | |
| 495 void handleControlMessage(message) { | |
| 496 switch (message[0]) { | |
| 497 case "pause": | |
| 498 addPause(message[1], message[2]); | |
| 499 break; | |
| 500 case "resume": | |
| 501 removePause(message[1]); | |
| 502 break; | |
| 503 case 'add-ondone': | |
| 504 addDoneListener(message[1], message[2]); | |
| 505 break; | |
| 506 case 'remove-ondone': | |
| 507 removeDoneListener(message[1]); | |
| 508 break; | |
| 509 case 'set-errors-fatal': | |
| 510 setErrorsFatal(message[1], message[2]); | |
| 511 break; | |
| 512 case "ping": | |
| 513 handlePing(message[1], message[2], message[3]); | |
| 514 break; | |
| 515 case "kill": | |
| 516 handleKill(message[1], message[2]); | |
| 517 break; | |
| 518 case "getErrors": | |
| 519 addErrorListener(message[1]); | |
| 520 break; | |
| 521 case "stopErrors": | |
| 522 removeErrorListener(message[1]); | |
| 523 break; | |
| 524 default: | |
| 525 } | |
| 526 } | |
| 527 | |
| 528 /** Looks up a port registered for this isolate. */ | |
| 529 RawReceivePortImpl lookup(int portId) => ports[portId]; | |
| 530 | |
| 531 void _addRegistration(int portId, RawReceivePortImpl port) { | |
| 532 if (ports.containsKey(portId)) { | |
| 533 throw new Exception("Registry: ports must be registered only once."); | |
| 534 } | |
| 535 ports[portId] = port; | |
| 536 } | |
| 537 | |
| 538 /** Registers a port on this isolate. */ | |
| 539 void register(int portId, RawReceivePortImpl port) { | |
| 540 _addRegistration(portId, port); | |
| 541 _updateGlobalState(); | |
| 542 } | |
| 543 | |
| 544 /** | |
| 545 * Registers a weak port on this isolate. | |
| 546 * | |
| 547 * The port does not keep the isolate active. | |
| 548 */ | |
| 549 void registerWeak(int portId, RawReceivePortImpl port) { | |
| 550 weakPorts.add(portId); | |
| 551 _addRegistration(portId, port); | |
| 552 } | |
| 553 | |
| 554 void _updateGlobalState() { | |
| 555 if (ports.length - weakPorts.length > 0 || isPaused || !initialized) { | |
| 556 _globalState.isolates[id] = this; // indicate this isolate is active | |
| 557 } else { | |
| 558 kill(); | |
| 559 } | |
| 560 } | |
| 561 | |
| 562 void kill() { | |
| 563 if (_scheduledControlEvents != null) { | |
| 564 // Kill all pending events. | |
| 565 _scheduledControlEvents.clear(); | |
| 566 } | |
| 567 // Stop listening on all ports. | |
| 568 // This should happen before sending events to done handlers, in case | |
| 569 // we are listening on ourselves. | |
| 570 // Closes all ports, including control port. | |
| 571 for (var port in ports.values) { | |
| 572 port._close(); | |
| 573 } | |
| 574 ports.clear(); | |
| 575 weakPorts.clear(); | |
| 576 _globalState.isolates.remove(id); // indicate this isolate is not active | |
| 577 errorPorts.clear(); | |
| 578 if (doneHandlers != null) { | |
| 579 for (int i = 0; i < doneHandlers.length; i += 2) { | |
| 580 SendPort responsePort = doneHandlers[i]; | |
| 581 Object response = doneHandlers[i + 1]; | |
| 582 responsePort.send(response); | |
| 583 } | |
| 584 doneHandlers = null; | |
| 585 } | |
| 586 } | |
| 587 | |
| 588 /** Unregister a port on this isolate. */ | |
| 589 void unregister(int portId) { | |
| 590 ports.remove(portId); | |
| 591 weakPorts.remove(portId); | |
| 592 _updateGlobalState(); | |
| 593 } | |
| 594 } | |
| 595 | |
| 596 /** Represent the event loop on a javascript thread (DOM or worker). */ | |
| 597 class _EventLoop { | |
| 598 final Queue<_IsolateEvent> events = new Queue<_IsolateEvent>(); | |
| 599 | |
| 600 /// The number of waiting callbacks not controlled by the dart event loop. | |
| 601 /// | |
| 602 /// This could be timers or http requests. The worker will only be killed if | |
| 603 /// this count reaches 0. | |
| 604 /// Access this by using [enterJsAsync] before starting a JavaScript async | |
| 605 /// operation and [leaveJsAsync] when the callback has fired. | |
| 606 int _activeJsAsyncCount = 0; | |
| 607 | |
| 608 _EventLoop(); | |
| 609 | |
| 610 void enqueue(isolate, fn, msg) { | |
| 611 events.addLast(new _IsolateEvent(isolate, fn, msg)); | |
| 612 } | |
| 613 | |
| 614 void prequeue(_IsolateEvent event) { | |
| 615 events.addFirst(event); | |
| 616 } | |
| 617 | |
| 618 _IsolateEvent dequeue() { | |
| 619 if (events.isEmpty) return null; | |
| 620 return events.removeFirst(); | |
| 621 } | |
| 622 | |
| 623 void checkOpenReceivePortsFromCommandLine() { | |
| 624 if (_globalState.rootContext != null | |
| 625 && _globalState.isolates.containsKey(_globalState.rootContext.id) | |
| 626 && _globalState.fromCommandLine | |
| 627 && _globalState.rootContext.ports.isEmpty) { | |
| 628 // We want to reach here only on the main [_Manager] and only | |
| 629 // on the command-line. In the browser the isolate might | |
| 630 // still be alive due to DOM callbacks, but the presumption is | |
| 631 // that on the command-line, no future events can be injected | |
| 632 // into the event queue once it's empty. Node has setTimeout | |
| 633 // so this presumption is incorrect there. We think(?) that | |
| 634 // in d8 this assumption is valid. | |
| 635 throw new Exception("Program exited with open ReceivePorts."); | |
| 636 } | |
| 637 } | |
| 638 | |
| 639 /** Process a single event, if any. */ | |
| 640 bool runIteration() { | |
| 641 final event = dequeue(); | |
| 642 if (event == null) { | |
| 643 checkOpenReceivePortsFromCommandLine(); | |
| 644 _globalState.maybeCloseWorker(); | |
| 645 return false; | |
| 646 } | |
| 647 event.process(); | |
| 648 return true; | |
| 649 } | |
| 650 | |
| 651 /** | |
| 652 * Runs multiple iterations of the run-loop. If possible, each iteration is | |
| 653 * run asynchronously. | |
| 654 */ | |
| 655 void _runHelper() { | |
| 656 if (globalWindow != null) { | |
| 657 // Run each iteration from the browser's top event loop. | |
| 658 void next() { | |
| 659 if (!runIteration()) return; | |
| 660 Timer.run(next); | |
| 661 } | |
| 662 next(); | |
| 663 } else { | |
| 664 // Run synchronously until no more iterations are available. | |
| 665 while (runIteration()) {} | |
| 666 } | |
| 667 } | |
| 668 | |
| 669 /** | |
| 670 * Call [_runHelper] but ensure that worker exceptions are propagated. | |
| 671 */ | |
| 672 void run() { | |
| 673 if (!_globalState.isWorker) { | |
| 674 _runHelper(); | |
| 675 } else { | |
| 676 try { | |
| 677 _runHelper(); | |
| 678 } catch (e, trace) { | |
| 679 _globalState.mainManager.postMessage(_serializeMessage( | |
| 680 {'command': 'error', 'msg': '$e\n$trace' })); | |
| 681 } | |
| 682 } | |
| 683 } | |
| 684 } | |
| 685 | |
| 686 /** An event in the top-level event queue. */ | |
| 687 class _IsolateEvent { | |
| 688 _IsolateContext isolate; | |
| 689 Function fn; | |
| 690 String message; | |
| 691 | |
| 692 _IsolateEvent(this.isolate, this.fn, this.message); | |
| 693 | |
| 694 void process() { | |
| 695 if (isolate.isPaused) { | |
| 696 isolate.delayedEvents.add(this); | |
| 697 return; | |
| 698 } | |
| 699 isolate.eval(fn); | |
| 700 } | |
| 701 } | |
| 702 | |
| 703 /** A stub for interacting with the main manager. */ | |
| 704 class _MainManagerStub { | |
| 705 void postMessage(msg) { | |
| 706 // "self" is a way to refer to the global context object that | |
| 707 // works in HTML pages and in Web Workers. It does not work in d8 | |
| 708 // and Firefox jsshell, because that would have been too easy. | |
| 709 // | |
| 710 // See: http://www.w3.org/TR/workers/#the-global-scope | |
| 711 // and: http://www.w3.org/TR/Window/#dfn-self-attribute | |
| 712 requiresPreamble(); | |
| 713 JS("void", r"self.postMessage(#)", msg); | |
| 714 } | |
| 715 } | |
| 716 | |
| 717 const String _SPAWNED_SIGNAL = "spawned"; | |
| 718 const String _SPAWN_FAILED_SIGNAL = "spawn failed"; | |
| 719 | |
| 720 get globalWindow { | |
| 721 requiresPreamble(); | |
| 722 return JS('', "self.window"); | |
| 723 } | |
| 724 | |
| 725 get globalWorker { | |
| 726 requiresPreamble(); | |
| 727 return JS('', "self.Worker"); | |
| 728 } | |
| 729 bool get globalPostMessageDefined { | |
| 730 requiresPreamble(); | |
| 731 return JS('bool', "!!self.postMessage"); | |
| 732 } | |
| 733 | |
| 734 typedef _MainFunction(); | |
| 735 typedef _MainFunctionArgs(args); | |
| 736 typedef _MainFunctionArgsMessage(args, message); | |
| 737 | |
| 738 /// Note: IsolateNatives depends on _globalState which is only set up correctly | |
| 739 /// when 'dart:isolate' has been imported. | |
| 740 class IsolateNatives { | |
| 741 | |
| 742 // We set [enableSpawnWorker] to true (not null) when calling isolate | |
| 743 // primitives that require support for spawning workers. The field starts out | |
| 744 // by being null, and dart2js' type inference will track if it can have a | |
| 745 // non-null value. So by testing if this value is not null, we generate code | |
| 746 // that dart2js knows is dead when worker support isn't needed. | |
| 747 // TODO(herhut): Initialize this to false when able to track compile-time | |
| 748 // constants. | |
| 749 static var enableSpawnWorker; | |
| 750 | |
| 751 static String thisScript = computeThisScript(); | |
| 752 | |
| 753 /// Associates an ID with a native worker object. | |
| 754 static final Expando<int> workerIds = new Expando<int>(); | |
| 755 | |
| 756 /** | |
| 757 * The src url for the script tag that loaded this function. | |
| 758 * | |
| 759 * Used to create JavaScript workers and load deferred libraries. | |
| 760 */ | |
| 761 static String computeThisScript() { | |
| 762 var currentScript = JS_EMBEDDED_GLOBAL('', CURRENT_SCRIPT); | |
| 763 if (currentScript != null) { | |
| 764 return JS('String', 'String(#.src)', currentScript); | |
| 765 } | |
| 766 // A worker has no script tag - so get an url from a stack-trace. | |
| 767 if (_globalState.isWorker) return computeThisScriptFromTrace(); | |
| 768 return null; | |
| 769 } | |
| 770 | |
| 771 static String computeThisScriptFromTrace() { | |
| 772 var stack = JS('String|Null', 'new Error().stack'); | |
| 773 if (stack == null) { | |
| 774 // According to Internet Explorer documentation, the stack | |
| 775 // property is not set until the exception is thrown. The stack | |
| 776 // property was not provided until IE10. | |
| 777 stack = JS('String|Null', | |
| 778 '(function() {' | |
| 779 'try { throw new Error() } catch(e) { return e.stack }' | |
| 780 '})()'); | |
| 781 if (stack == null) throw new UnsupportedError('No stack trace'); | |
| 782 } | |
| 783 var pattern, matches; | |
| 784 | |
| 785 // This pattern matches V8, Chrome, and Internet Explorer stack | |
| 786 // traces that look like this: | |
| 787 // Error | |
| 788 // at methodName (URI:LINE:COLUMN) | |
| 789 pattern = JS('', | |
| 790 r'new RegExp("^ *at [^(]*\\((.*):[0-9]*:[0-9]*\\)$", "m")'); | |
| 791 | |
| 792 | |
| 793 matches = JS('JSExtendableArray|Null', '#.match(#)', stack, pattern); | |
| 794 if (matches != null) return JS('String', '#[1]', matches); | |
| 795 | |
| 796 // This pattern matches Firefox stack traces that look like this: | |
| 797 // methodName@URI:LINE | |
| 798 pattern = JS('', r'new RegExp("^[^@]*@(.*):[0-9]*$", "m")'); | |
| 799 | |
| 800 matches = JS('JSExtendableArray|Null', '#.match(#)', stack, pattern); | |
| 801 if (matches != null) return JS('String', '#[1]', matches); | |
| 802 | |
| 803 throw new UnsupportedError('Cannot extract URI from "$stack"'); | |
| 804 } | |
| 805 | |
| 806 /** | |
| 807 * Assume that [e] is a browser message event and extract its message data. | |
| 808 * We don't import the dom explicitly so, when workers are disabled, this | |
| 809 * library can also run on top of nodejs. | |
| 810 */ | |
| 811 static _getEventData(e) => JS("", "#.data", e); | |
| 812 | |
| 813 /** | |
| 814 * Process messages on a worker, either to control the worker instance or to | |
| 815 * pass messages along to the isolate running in the worker. | |
| 816 */ | |
| 817 static void _processWorkerMessage(/* Worker */ sender, e) { | |
| 818 var msg = _deserializeMessage(_getEventData(e)); | |
| 819 switch (msg['command']) { | |
| 820 case 'start': | |
| 821 _globalState.currentManagerId = msg['id']; | |
| 822 String functionName = msg['functionName']; | |
| 823 Function entryPoint = (functionName == null) | |
| 824 ? _globalState.entry | |
| 825 : _getJSFunctionFromName(functionName); | |
| 826 var args = msg['args']; | |
| 827 var message = _deserializeMessage(msg['msg']); | |
| 828 var isSpawnUri = msg['isSpawnUri']; | |
| 829 var startPaused = msg['startPaused']; | |
| 830 var replyTo = _deserializeMessage(msg['replyTo']); | |
| 831 var context = new _IsolateContext(); | |
| 832 _globalState.topEventLoop.enqueue(context, () { | |
| 833 _startIsolate(entryPoint, args, message, | |
| 834 isSpawnUri, startPaused, replyTo); | |
| 835 }, 'worker-start'); | |
| 836 // Make sure we always have a current context in this worker. | |
| 837 // TODO(7907): This is currently needed because we're using | |
| 838 // Timers to implement Futures, and this isolate library | |
| 839 // implementation uses Futures. We should either stop using | |
| 840 // Futures in this library, or re-adapt if Futures get a | |
| 841 // different implementation. | |
| 842 _globalState.currentContext = context; | |
| 843 _globalState.topEventLoop.run(); | |
| 844 break; | |
| 845 case 'spawn-worker': | |
| 846 if (enableSpawnWorker != null) handleSpawnWorkerRequest(msg); | |
| 847 break; | |
| 848 case 'message': | |
| 849 SendPort port = msg['port']; | |
| 850 // If the port has been closed, we ignore the message. | |
| 851 if (port != null) { | |
| 852 msg['port'].send(msg['msg']); | |
| 853 } | |
| 854 _globalState.topEventLoop.run(); | |
| 855 break; | |
| 856 case 'close': | |
| 857 _globalState.managers.remove(workerIds[sender]); | |
| 858 JS('void', '#.terminate()', sender); | |
| 859 _globalState.topEventLoop.run(); | |
| 860 break; | |
| 861 case 'log': | |
| 862 _log(msg['msg']); | |
| 863 break; | |
| 864 case 'print': | |
| 865 if (_globalState.isWorker) { | |
| 866 _globalState.mainManager.postMessage( | |
| 867 _serializeMessage({'command': 'print', 'msg': msg})); | |
| 868 } else { | |
| 869 print(msg['msg']); | |
| 870 } | |
| 871 break; | |
| 872 case 'error': | |
| 873 throw msg['msg']; | |
| 874 } | |
| 875 } | |
| 876 | |
| 877 static handleSpawnWorkerRequest(msg) { | |
| 878 var replyPort = msg['replyPort']; | |
| 879 spawn(msg['functionName'], msg['uri'], | |
| 880 msg['args'], msg['msg'], | |
| 881 false, msg['isSpawnUri'], msg['startPaused']).then((msg) { | |
| 882 replyPort.send(msg); | |
| 883 }, onError: (String errorMessage) { | |
| 884 replyPort.send([_SPAWN_FAILED_SIGNAL, errorMessage]); | |
| 885 }); | |
| 886 } | |
| 887 | |
| 888 /** Log a message, forwarding to the main [_Manager] if appropriate. */ | |
| 889 static _log(msg) { | |
| 890 if (_globalState.isWorker) { | |
| 891 _globalState.mainManager.postMessage( | |
| 892 _serializeMessage({'command': 'log', 'msg': msg })); | |
| 893 } else { | |
| 894 try { | |
| 895 _consoleLog(msg); | |
| 896 } catch (e, trace) { | |
| 897 throw new Exception(trace); | |
| 898 } | |
| 899 } | |
| 900 } | |
| 901 | |
| 902 static void _consoleLog(msg) { | |
| 903 requiresPreamble(); | |
| 904 JS("void", r"self.console.log(#)", msg); | |
| 905 } | |
| 906 | |
| 907 static _getJSFunctionFromName(String functionName) { | |
| 908 var globalFunctionsContainer = JS_EMBEDDED_GLOBAL("", GLOBAL_FUNCTIONS); | |
| 909 return JS("", "#[#]()", globalFunctionsContainer, functionName); | |
| 910 } | |
| 911 | |
| 912 /** | |
| 913 * Get a string name for the function, if possible. The result for | |
| 914 * anonymous functions is browser-dependent -- it may be "" or "anonymous" | |
| 915 * but you should probably not count on this. | |
| 916 */ | |
| 917 static String _getJSFunctionName(Function f) { | |
| 918 return (f is Closure) ? JS("String|Null", r'#.$name', f) : null; | |
| 919 } | |
| 920 | |
| 921 /** Create a new JavaScript object instance given its constructor. */ | |
| 922 static dynamic _allocate(var ctor) { | |
| 923 return JS("", "new #()", ctor); | |
| 924 } | |
| 925 | |
| 926 static Future<List> spawnFunction(void topLevelFunction(message), | |
| 927 var message, | |
| 928 bool startPaused) { | |
| 929 IsolateNatives.enableSpawnWorker = true; | |
| 930 final name = _getJSFunctionName(topLevelFunction); | |
| 931 if (name == null) { | |
| 932 throw new UnsupportedError( | |
| 933 "only top-level functions can be spawned."); | |
| 934 } | |
| 935 bool isLight = false; | |
| 936 bool isSpawnUri = false; | |
| 937 return spawn(name, null, null, message, isLight, isSpawnUri, startPaused); | |
| 938 } | |
| 939 | |
| 940 static Future<List> spawnUri(Uri uri, List<String> args, var message, | |
| 941 bool startPaused) { | |
| 942 IsolateNatives.enableSpawnWorker = true; | |
| 943 bool isLight = false; | |
| 944 bool isSpawnUri = true; | |
| 945 return spawn(null, uri.toString(), args, message, | |
| 946 isLight, isSpawnUri, startPaused); | |
| 947 } | |
| 948 | |
| 949 // TODO(sigmund): clean up above, after we make the new API the default: | |
| 950 | |
| 951 /// If [uri] is `null` it is replaced with the current script. | |
| 952 static Future<List> spawn(String functionName, String uri, | |
| 953 List<String> args, message, | |
| 954 bool isLight, bool isSpawnUri, bool startPaused) { | |
| 955 // Assume that the compiled version of the Dart file lives just next to the | |
| 956 // dart file. | |
| 957 // TODO(floitsch): support precompiled version of dart2js output. | |
| 958 if (uri != null && uri.endsWith(".dart")) uri += ".js"; | |
| 959 | |
| 960 ReceivePort port = new ReceivePort(); | |
| 961 Completer<List> completer = new Completer(); | |
| 962 port.first.then((msg) { | |
| 963 if (msg[0] == _SPAWNED_SIGNAL) { | |
| 964 completer.complete(msg); | |
| 965 } else { | |
| 966 assert(msg[0] == _SPAWN_FAILED_SIGNAL); | |
| 967 completer.completeError(msg[1]); | |
| 968 } | |
| 969 }); | |
| 970 | |
| 971 SendPort signalReply = port.sendPort; | |
| 972 | |
| 973 if (_globalState.useWorkers && !isLight) { | |
| 974 _startWorker( | |
| 975 functionName, uri, args, message, isSpawnUri, startPaused, | |
| 976 signalReply, (String message) => completer.completeError(message)); | |
| 977 } else { | |
| 978 _startNonWorker( | |
| 979 functionName, uri, args, message, isSpawnUri, startPaused, | |
| 980 signalReply); | |
| 981 } | |
| 982 return completer.future; | |
| 983 } | |
| 984 | |
| 985 static void _startWorker( | |
| 986 String functionName, String uri, | |
| 987 List<String> args, message, | |
| 988 bool isSpawnUri, | |
| 989 bool startPaused, | |
| 990 SendPort replyPort, | |
| 991 void onError(String message)) { | |
| 992 // Make sure that the args list is a fresh generic list. A newly spawned | |
| 993 // isolate should be able to assume that the arguments list is an | |
| 994 // extendable list. | |
| 995 if (args != null) args = new List<String>.from(args); | |
| 996 if (_globalState.isWorker) { | |
| 997 _globalState.mainManager.postMessage(_serializeMessage({ | |
| 998 'command': 'spawn-worker', | |
| 999 'functionName': functionName, | |
| 1000 'args': args, | |
| 1001 'msg': message, | |
| 1002 'uri': uri, | |
| 1003 'isSpawnUri': isSpawnUri, | |
| 1004 'startPaused': startPaused, | |
| 1005 'replyPort': replyPort})); | |
| 1006 } else { | |
| 1007 _spawnWorker(functionName, uri, args, message, | |
| 1008 isSpawnUri, startPaused, replyPort, onError); | |
| 1009 } | |
| 1010 } | |
| 1011 | |
| 1012 static void _startNonWorker( | |
| 1013 String functionName, String uri, | |
| 1014 List<String> args, var message, | |
| 1015 bool isSpawnUri, | |
| 1016 bool startPaused, | |
| 1017 SendPort replyPort) { | |
| 1018 // TODO(eub): support IE9 using an iframe -- Dart issue 1702. | |
| 1019 if (uri != null) { | |
| 1020 throw new UnsupportedError( | |
| 1021 "Currently spawnUri is not supported without web workers."); | |
| 1022 } | |
| 1023 // Clone the message to enforce the restrictions we have on isolate | |
| 1024 // messages. | |
| 1025 message = _clone(message); | |
| 1026 // Make sure that the args list is a fresh generic list. A newly spawned | |
| 1027 // isolate should be able to assume that the arguments list is an | |
| 1028 // extendable list. | |
| 1029 if (args != null) args = new List<String>.from(args); | |
| 1030 _globalState.topEventLoop.enqueue(new _IsolateContext(), () { | |
| 1031 final func = _getJSFunctionFromName(functionName); | |
| 1032 _startIsolate(func, args, message, isSpawnUri, startPaused, replyPort); | |
| 1033 }, 'nonworker start'); | |
| 1034 } | |
| 1035 | |
| 1036 static Isolate get currentIsolate { | |
| 1037 _IsolateContext context = JS_CURRENT_ISOLATE_CONTEXT(); | |
| 1038 return new Isolate(context.controlPort.sendPort, | |
| 1039 pauseCapability: context.pauseCapability, | |
| 1040 terminateCapability: context.terminateCapability); | |
| 1041 } | |
| 1042 | |
| 1043 static void _startIsolate(Function topLevel, | |
| 1044 List<String> args, message, | |
| 1045 bool isSpawnUri, | |
| 1046 bool startPaused, | |
| 1047 SendPort replyTo) { | |
| 1048 _IsolateContext context = JS_CURRENT_ISOLATE_CONTEXT(); | |
| 1049 Primitives.initializeStatics(context.id); | |
| 1050 // The isolate's port does not keep the isolate open. | |
| 1051 replyTo.send([_SPAWNED_SIGNAL, | |
| 1052 context.controlPort.sendPort, | |
| 1053 context.pauseCapability, | |
| 1054 context.terminateCapability]); | |
| 1055 | |
| 1056 void runStartFunction() { | |
| 1057 context.initialized = true; | |
| 1058 if (!isSpawnUri) { | |
| 1059 topLevel(message); | |
| 1060 } else if (topLevel is _MainFunctionArgsMessage) { | |
| 1061 topLevel(args, message); | |
| 1062 } else if (topLevel is _MainFunctionArgs) { | |
| 1063 topLevel(args); | |
| 1064 } else { | |
| 1065 topLevel(); | |
| 1066 } | |
| 1067 } | |
| 1068 | |
| 1069 if (startPaused) { | |
| 1070 context.addPause(context.pauseCapability, context.pauseCapability); | |
| 1071 _globalState.topEventLoop.enqueue(context, runStartFunction, | |
| 1072 'start isolate'); | |
| 1073 } else { | |
| 1074 runStartFunction(); | |
| 1075 } | |
| 1076 } | |
| 1077 | |
| 1078 /** | |
| 1079 * Spawns an isolate in a worker. [factoryName] is the Javascript constructor | |
| 1080 * name for the isolate entry point class. | |
| 1081 */ | |
| 1082 static void _spawnWorker(functionName, String uri, | |
| 1083 List<String> args, message, | |
| 1084 bool isSpawnUri, | |
| 1085 bool startPaused, | |
| 1086 SendPort replyPort, | |
| 1087 void onError(String message)) { | |
| 1088 if (uri == null) uri = thisScript; | |
| 1089 final worker = JS('var', 'new Worker(#)', uri); | |
| 1090 // Trampolines are used when wanting to call a Dart closure from | |
| 1091 // JavaScript. The helper function DART_CLOSURE_TO_JS only accepts | |
| 1092 // top-level or static methods, and the trampoline allows us to capture | |
| 1093 // arguments and values which can be passed to a static method. | |
| 1094 final onerrorTrampoline = JS( | |
| 1095 '', | |
| 1096 ''' | |
| 1097 (function (f, u, c) { | |
| 1098 return function(e) { | |
| 1099 return f(e, u, c) | |
| 1100 } | |
| 1101 })(#, #, #)''', | |
| 1102 DART_CLOSURE_TO_JS(workerOnError), uri, onError); | |
| 1103 JS('void', '#.onerror = #', worker, onerrorTrampoline); | |
| 1104 | |
| 1105 var processWorkerMessageTrampoline = JS( | |
| 1106 '', | |
| 1107 """ | |
| 1108 (function (f, a) { | |
| 1109 return function (e) { | |
| 1110 // We can stop listening for errors when the first message is received as | |
| 1111 // we only listen for messages to determine if the uri was bad. | |
| 1112 e.onerror = null; | |
| 1113 return f(a, e); | |
| 1114 } | |
| 1115 })(#, #)""", | |
| 1116 DART_CLOSURE_TO_JS(_processWorkerMessage), | |
| 1117 worker); | |
| 1118 JS('void', '#.onmessage = #', worker, processWorkerMessageTrampoline); | |
| 1119 var workerId = _globalState.nextManagerId++; | |
| 1120 // We also store the id on the worker itself so that we can unregister it. | |
| 1121 workerIds[worker] = workerId; | |
| 1122 _globalState.managers[workerId] = worker; | |
| 1123 JS('void', '#.postMessage(#)', worker, _serializeMessage({ | |
| 1124 'command': 'start', | |
| 1125 'id': workerId, | |
| 1126 // Note: we serialize replyPort twice because the child worker needs to | |
| 1127 // first deserialize the worker id, before it can correctly deserialize | |
| 1128 // the port (port deserialization is sensitive to what is the current | |
| 1129 // workerId). | |
| 1130 'replyTo': _serializeMessage(replyPort), | |
| 1131 'args': args, | |
| 1132 'msg': _serializeMessage(message), | |
| 1133 'isSpawnUri': isSpawnUri, | |
| 1134 'startPaused': startPaused, | |
| 1135 'functionName': functionName })); | |
| 1136 } | |
| 1137 | |
| 1138 static bool workerOnError( | |
| 1139 /* Event */ event, | |
| 1140 String uri, | |
| 1141 void onError(String message)) { | |
| 1142 // Attempt to shut up the browser, as the error has been handled. Chrome | |
| 1143 // ignores this :-( | |
| 1144 JS('void', '#.preventDefault()', event); | |
| 1145 String message = JS('String|Null', '#.message', event); | |
| 1146 if (message == null) { | |
| 1147 // Some browsers, including Chrome, fail to provide a proper error | |
| 1148 // event. | |
| 1149 message = 'Error spawning worker for $uri'; | |
| 1150 } else { | |
| 1151 message = 'Error spawning worker for $uri ($message)'; | |
| 1152 } | |
| 1153 onError(message); | |
| 1154 return true; | |
| 1155 } | |
| 1156 } | |
| 1157 | |
| 1158 /******************************************************** | |
| 1159 Inserted from lib/isolate/dart2js/ports.dart | |
| 1160 ********************************************************/ | |
| 1161 | |
| 1162 /** Common functionality to all send ports. */ | |
| 1163 abstract class _BaseSendPort implements SendPort { | |
| 1164 /** Id for the destination isolate. */ | |
| 1165 final int _isolateId; | |
| 1166 | |
| 1167 const _BaseSendPort(this._isolateId); | |
| 1168 | |
| 1169 void _checkReplyTo(SendPort replyTo) { | |
| 1170 if (replyTo != null | |
| 1171 && replyTo is! _NativeJsSendPort | |
| 1172 && replyTo is! _WorkerSendPort) { | |
| 1173 throw new Exception("SendPort.send: Illegal replyTo port type"); | |
| 1174 } | |
| 1175 } | |
| 1176 | |
| 1177 void send(var message); | |
| 1178 bool operator ==(var other); | |
| 1179 int get hashCode; | |
| 1180 } | |
| 1181 | |
| 1182 /** A send port that delivers messages in-memory via native JavaScript calls. */ | |
| 1183 class _NativeJsSendPort extends _BaseSendPort implements SendPort { | |
| 1184 final RawReceivePortImpl _receivePort; | |
| 1185 | |
| 1186 const _NativeJsSendPort(this._receivePort, int isolateId) : super(isolateId); | |
| 1187 | |
| 1188 void send(var message) { | |
| 1189 // Check that the isolate still runs and the port is still open | |
| 1190 final isolate = _globalState.isolates[_isolateId]; | |
| 1191 if (isolate == null) return; | |
| 1192 if (_receivePort._isClosed) return; | |
| 1193 // Clone the message to enforce the restrictions we have on isolate | |
| 1194 // messages. | |
| 1195 var msg = _clone(message); | |
| 1196 if (isolate.controlPort == _receivePort) { | |
| 1197 isolate.handleControlMessage(msg); | |
| 1198 return; | |
| 1199 } | |
| 1200 _globalState.topEventLoop.enqueue(isolate, () { | |
| 1201 if (!_receivePort._isClosed) { | |
| 1202 _receivePort._add(msg); | |
| 1203 } | |
| 1204 }, 'receive $message'); | |
| 1205 } | |
| 1206 | |
| 1207 bool operator ==(var other) => (other is _NativeJsSendPort) && | |
| 1208 (_receivePort == other._receivePort); | |
| 1209 | |
| 1210 int get hashCode => _receivePort._id; | |
| 1211 } | |
| 1212 | |
| 1213 /** A send port that delivers messages via worker.postMessage. */ | |
| 1214 // TODO(eub): abstract this for iframes. | |
| 1215 class _WorkerSendPort extends _BaseSendPort implements SendPort { | |
| 1216 final int _workerId; | |
| 1217 final int _receivePortId; | |
| 1218 | |
| 1219 const _WorkerSendPort(this._workerId, int isolateId, this._receivePortId) | |
| 1220 : super(isolateId); | |
| 1221 | |
| 1222 void send(var message) { | |
| 1223 final workerMessage = _serializeMessage({ | |
| 1224 'command': 'message', | |
| 1225 'port': this, | |
| 1226 'msg': message}); | |
| 1227 | |
| 1228 if (_globalState.isWorker) { | |
| 1229 // Communication from one worker to another go through the | |
| 1230 // main worker. | |
| 1231 _globalState.mainManager.postMessage(workerMessage); | |
| 1232 } else { | |
| 1233 // Deliver the message only if the worker is still alive. | |
| 1234 /* Worker */ var manager = _globalState.managers[_workerId]; | |
| 1235 if (manager != null) { | |
| 1236 JS('void', '#.postMessage(#)', manager, workerMessage); | |
| 1237 } | |
| 1238 } | |
| 1239 } | |
| 1240 | |
| 1241 bool operator ==(var other) { | |
| 1242 return (other is _WorkerSendPort) && | |
| 1243 (_workerId == other._workerId) && | |
| 1244 (_isolateId == other._isolateId) && | |
| 1245 (_receivePortId == other._receivePortId); | |
| 1246 } | |
| 1247 | |
| 1248 int get hashCode { | |
| 1249 // TODO(sigmund): use a standard hash when we get one available in corelib. | |
| 1250 return (_workerId << 16) ^ (_isolateId << 8) ^ _receivePortId; | |
| 1251 } | |
| 1252 } | |
| 1253 | |
| 1254 class RawReceivePortImpl implements RawReceivePort { | |
| 1255 static int _nextFreeId = 1; | |
| 1256 | |
| 1257 final int _id; | |
| 1258 Function _handler; | |
| 1259 bool _isClosed = false; | |
| 1260 | |
| 1261 RawReceivePortImpl(this._handler) : _id = _nextFreeId++ { | |
| 1262 _globalState.currentContext.register(_id, this); | |
| 1263 } | |
| 1264 | |
| 1265 RawReceivePortImpl.weak(this._handler) : _id = _nextFreeId++ { | |
| 1266 _globalState.currentContext.registerWeak(_id, this); | |
| 1267 } | |
| 1268 | |
| 1269 // Creates the control port of an isolate. | |
| 1270 // This is created before the isolate context object itself, | |
| 1271 // so it cannot access the static _nextFreeId field. | |
| 1272 RawReceivePortImpl._controlPort() : _handler = null, _id = 0; | |
| 1273 | |
| 1274 void set handler(Function newHandler) { | |
| 1275 _handler = newHandler; | |
| 1276 } | |
| 1277 | |
| 1278 // Close the port without unregistering it. | |
| 1279 // Used by an isolate context to close all ports when shutting down. | |
| 1280 void _close() { | |
| 1281 _isClosed = true; | |
| 1282 _handler = null; | |
| 1283 } | |
| 1284 | |
| 1285 void close() { | |
| 1286 if (_isClosed) return; | |
| 1287 _isClosed = true; | |
| 1288 _handler = null; | |
| 1289 _globalState.currentContext.unregister(_id); | |
| 1290 } | |
| 1291 | |
| 1292 void _add(dataEvent) { | |
| 1293 if (_isClosed) return; | |
| 1294 _handler(dataEvent); | |
| 1295 } | |
| 1296 | |
| 1297 SendPort get sendPort { | |
| 1298 return new _NativeJsSendPort(this, _globalState.currentContext.id); | |
| 1299 } | |
| 1300 } | |
| 1301 | |
| 1302 class ReceivePortImpl extends Stream implements ReceivePort { | |
| 1303 final RawReceivePort _rawPort; | |
| 1304 StreamController _controller; | |
| 1305 | |
| 1306 ReceivePortImpl() : this.fromRawReceivePort(new RawReceivePortImpl(null)); | |
| 1307 | |
| 1308 ReceivePortImpl.weak() | |
| 1309 : this.fromRawReceivePort(new RawReceivePortImpl.weak(null)); | |
| 1310 | |
| 1311 ReceivePortImpl.fromRawReceivePort(this._rawPort) { | |
| 1312 _controller = new StreamController(onCancel: close, sync: true); | |
| 1313 _rawPort.handler = _controller.add; | |
| 1314 } | |
| 1315 | |
| 1316 StreamSubscription listen(void onData(var event), | |
| 1317 {Function onError, | |
| 1318 void onDone(), | |
| 1319 bool cancelOnError}) { | |
| 1320 return _controller.stream.listen(onData, onError: onError, onDone: onDone, | |
| 1321 cancelOnError: cancelOnError); | |
| 1322 } | |
| 1323 | |
| 1324 void close() { | |
| 1325 _rawPort.close(); | |
| 1326 _controller.close(); | |
| 1327 } | |
| 1328 | |
| 1329 SendPort get sendPort => _rawPort.sendPort; | |
| 1330 } | |
| 1331 | |
| 1332 class TimerImpl implements Timer { | |
| 1333 final bool _once; | |
| 1334 bool _inEventLoop = false; | |
| 1335 int _handle; | |
| 1336 | |
| 1337 TimerImpl(int milliseconds, void callback()) | |
| 1338 : _once = true { | |
| 1339 if (milliseconds == 0 && (!hasTimer() || _globalState.isWorker)) { | |
| 1340 | |
| 1341 void internalCallback() { | |
| 1342 _handle = null; | |
| 1343 callback(); | |
| 1344 } | |
| 1345 | |
| 1346 // Setting _handle to something different from null indicates that the | |
| 1347 // callback has not been run. Hence, the choice of 1 is arbitrary. | |
| 1348 _handle = 1; | |
| 1349 | |
| 1350 // This makes a dependency between the async library and the | |
| 1351 // event loop of the isolate library. The compiler makes sure | |
| 1352 // that the event loop is compiled if [Timer] is used. | |
| 1353 // TODO(7907): In case of web workers, we need to use the event | |
| 1354 // loop instead of setTimeout, to make sure the futures get executed in | |
| 1355 // order. | |
| 1356 _globalState.topEventLoop.enqueue( | |
| 1357 _globalState.currentContext, internalCallback, 'timer'); | |
| 1358 _inEventLoop = true; | |
| 1359 } else if (hasTimer()) { | |
| 1360 | |
| 1361 void internalCallback() { | |
| 1362 _handle = null; | |
| 1363 leaveJsAsync(); | |
| 1364 callback(); | |
| 1365 } | |
| 1366 | |
| 1367 enterJsAsync(); | |
| 1368 | |
| 1369 _handle = JS('int', 'self.setTimeout(#, #)', | |
| 1370 convertDartClosureToJS(internalCallback, 0), | |
| 1371 milliseconds); | |
| 1372 } else { | |
| 1373 assert(milliseconds > 0); | |
| 1374 throw new UnsupportedError("Timer greater than 0."); | |
| 1375 } | |
| 1376 } | |
| 1377 | |
| 1378 TimerImpl.periodic(int milliseconds, void callback(Timer timer)) | |
| 1379 : _once = false { | |
| 1380 if (hasTimer()) { | |
| 1381 enterJsAsync(); | |
| 1382 _handle = JS('int', 'self.setInterval(#, #)', | |
| 1383 convertDartClosureToJS(() { callback(this); }, 0), | |
| 1384 milliseconds); | |
| 1385 } else { | |
| 1386 throw new UnsupportedError("Periodic timer."); | |
| 1387 } | |
| 1388 } | |
| 1389 | |
| 1390 void cancel() { | |
| 1391 if (hasTimer()) { | |
| 1392 if (_inEventLoop) { | |
| 1393 throw new UnsupportedError("Timer in event loop cannot be canceled."); | |
| 1394 } | |
| 1395 if (_handle == null) return; | |
| 1396 leaveJsAsync(); | |
| 1397 if (_once) { | |
| 1398 JS('void', 'self.clearTimeout(#)', _handle); | |
| 1399 } else { | |
| 1400 JS('void', 'self.clearInterval(#)', _handle); | |
| 1401 } | |
| 1402 _handle = null; | |
| 1403 } else { | |
| 1404 throw new UnsupportedError("Canceling a timer."); | |
| 1405 } | |
| 1406 } | |
| 1407 | |
| 1408 bool get isActive => _handle != null; | |
| 1409 } | |
| 1410 | |
| 1411 bool hasTimer() { | |
| 1412 requiresPreamble(); | |
| 1413 return JS('', 'self.setTimeout') != null; | |
| 1414 } | |
| 1415 | |
| 1416 | |
| 1417 /** | |
| 1418 * Implementation class for [Capability]. | |
| 1419 * | |
| 1420 * It has the same name to make it harder for users to distinguish. | |
| 1421 */ | |
| 1422 class CapabilityImpl implements Capability { | |
| 1423 /** Internal random secret identifying the capability. */ | |
| 1424 final int _id; | |
| 1425 | |
| 1426 CapabilityImpl() : this._internal(random64()); | |
| 1427 | |
| 1428 CapabilityImpl._internal(this._id); | |
| 1429 | |
| 1430 int get hashCode { | |
| 1431 // Thomas Wang 32 bit Mix. | |
| 1432 // http://www.concentric.net/~Ttwang/tech/inthash.htm | |
| 1433 // (via https://gist.github.com/badboy/6267743) | |
| 1434 int hash = _id; | |
| 1435 hash = (hash >> 0) ^ (hash ~/ 0x100000000); // To 32 bit from ~64. | |
| 1436 hash = (~hash + (hash << 15)) & 0xFFFFFFFF; | |
| 1437 hash ^= hash >> 12; | |
| 1438 hash = (hash * 5) & 0xFFFFFFFF; | |
| 1439 hash ^= hash >> 4; | |
| 1440 hash = (hash * 2057) & 0xFFFFFFFF; | |
| 1441 hash ^= hash >> 16; | |
| 1442 return hash; | |
| 1443 } | |
| 1444 | |
| 1445 bool operator==(Object other) { | |
| 1446 if (identical(other, this)) return true; | |
| 1447 if (other is CapabilityImpl) { | |
| 1448 return identical(_id, other._id); | |
| 1449 } | |
| 1450 return false; | |
| 1451 } | |
| 1452 } | |
| OLD | NEW |