File: script_runner.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (348 lines) | stat: -rw-r--r-- 13,611 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (C) 2010 Google, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "third_party/blink/renderer/core/script/script_runner.h"

#include <algorithm>

#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/task/single_thread_task_runner.h"
#include "base/trace_event/typed_macros.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/scriptable_document_parser.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/script/script_loader.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"

namespace {

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class RaceTaskPriority {
  kLowerPriority = 0,
  kNormalPriority = 1,
  kMaxValue = kNormalPriority,
};

const char* RaceTaskPriorityToString(RaceTaskPriority task_priority) {
  switch (task_priority) {
    case RaceTaskPriority::kLowerPriority:
      return "LowerPriority";
    case RaceTaskPriority::kNormalPriority:
      return "NormalPriority";
  }
}

void PostTaskWithLowPriorityUntilTimeout(
    const base::Location& from_here,
    base::OnceClosure task,
    base::TimeDelta timeout,
    scoped_refptr<base::SingleThreadTaskRunner> lower_priority_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> normal_priority_task_runner) {
  using RefCountedOnceClosure = base::RefCountedData<base::OnceClosure>;
  scoped_refptr<RefCountedOnceClosure> ref_counted_task =
      base::MakeRefCounted<RefCountedOnceClosure>(std::move(task));

  // |run_task_once| runs on both of |lower_priority_task_runner| and
  // |normal_priority_task_runner|. |run_task_once| guarantees that the given
  // |task| doesn't run more than once. |task| runs on either of
  // |lower_priority_task_runner| and |normal_priority_task_runner| whichever
  // comes first.
  auto run_task_once = [](scoped_refptr<RefCountedOnceClosure> ref_counted_task,
                          RaceTaskPriority task_priority,
                          base::TimeTicks post_task_time) {
    if (!ref_counted_task->data.is_null()) {
      auto duration = base::TimeTicks::Now() - post_task_time;
      std::move(ref_counted_task->data).Run();
      base::UmaHistogramEnumeration(
          "Blink.Script.PostTaskWithLowPriorityUntilTimeout.RaceTaskPriority",
          task_priority);
      base::UmaHistogramMediumTimes(
          "Blink.Script.PostTaskWithLowPriorityUntilTimeout.Time", duration);
      base::UmaHistogramMediumTimes(
          base::StrCat(
              {"Blink.Script.PostTaskWithLowPriorityUntilTimeout.Time.",
               RaceTaskPriorityToString(task_priority)}),
          duration);
    }
  };

  base::TimeTicks post_task_time = base::TimeTicks::Now();

  lower_priority_task_runner->PostTask(
      from_here,
      WTF::BindOnce(run_task_once, ref_counted_task,
                    RaceTaskPriority::kLowerPriority, post_task_time));

  normal_priority_task_runner->PostDelayedTask(
      from_here,
      WTF::BindOnce(run_task_once, ref_counted_task,
                    RaceTaskPriority::kNormalPriority, post_task_time),
      timeout);
}

}  // namespace

namespace blink {

void PostTaskWithLowPriorityUntilTimeoutForTesting(
    const base::Location& from_here,
    base::OnceClosure task,
    base::TimeDelta timeout,
    scoped_refptr<base::SingleThreadTaskRunner> lower_priority_task_runner,
    scoped_refptr<base::SingleThreadTaskRunner> normal_priority_task_runner) {
  PostTaskWithLowPriorityUntilTimeout(from_here, std::move(task), timeout,
                                      std::move(lower_priority_task_runner),
                                      std::move(normal_priority_task_runner));
}

ScriptRunner::ScriptRunner(Document* document)
    : document_(document),
      task_runner_(document->GetTaskRunner(TaskType::kNetworking)),
      low_priority_task_runner_(
          document->GetTaskRunner(TaskType::kLowPriorityScriptExecution)) {
  DCHECK(document);
}

void ScriptRunner::QueueScriptForExecution(PendingScript* pending_script,
                                           DelayReasons delay_reasons) {
  DCHECK(pending_script);
  DCHECK(delay_reasons & static_cast<DelayReasons>(DelayReason::kLoad));
  document_->IncrementLoadEventDelayCount();

  switch (pending_script->GetSchedulingType()) {
    case ScriptSchedulingType::kAsync:
      pending_async_scripts_.insert(pending_script, delay_reasons);
      break;

    case ScriptSchedulingType::kInOrder:
      pending_in_order_scripts_.push_back(pending_script);
      break;

    case ScriptSchedulingType::kForceInOrder:
      pending_force_in_order_scripts_.push_back(pending_script);
      pending_force_in_order_scripts_count_ += 1;
      break;

    default:
      NOTREACHED();
  }

  // Note that WatchForLoad() can immediately call PendingScriptFinished().
  pending_script->WatchForLoad(this);
}

void ScriptRunner::AddDelayReason(DelayReason delay_reason) {
  DCHECK(!IsActive(delay_reason));
  active_delay_reasons_ |= static_cast<DelayReasons>(delay_reason);
}

void ScriptRunner::RemoveDelayReason(DelayReason delay_reason) {
  DCHECK(IsActive(delay_reason));
  active_delay_reasons_ &= ~static_cast<DelayReasons>(delay_reason);

  HeapVector<Member<PendingScript>> pending_async_scripts(
      pending_async_scripts_.Keys());
  for (PendingScript* pending_script : pending_async_scripts) {
    RemoveDelayReasonFromScript(pending_script, delay_reason);
  }
}

void ScriptRunner::RemoveDelayReasonFromScript(PendingScript* pending_script,
                                               DelayReason delay_reason) {
  // |pending_script| can be null when |RemoveDelayReasonFromScript()| is called
  // via |PostDelayedTask()| below.
  if (!pending_script)
    return;

  auto it = pending_async_scripts_.find(pending_script);

  if (it == pending_async_scripts_.end())
    return;

  if (it->value &= ~static_cast<DelayReasons>(delay_reason)) {
    // The delay must be less than a few seconds because some scripts times out
    // otherwise. This is only applied to milestone based delay.
    const base::TimeDelta delay_limit =
        features::kDelayAsyncScriptExecutionDelayLimitParam.Get();
    if (!delay_limit.is_zero() && delay_reason == DelayReason::kLoad &&
        (it->value & static_cast<DelayReasons>(DelayReason::kMilestone))) {
      // PostDelayedTask to limit the delay amount of DelayAsyncScriptExecution
      // (see crbug/1340837). DelayReason::kMilestone is sent on
      // loading-milestones such as LCP, first_paint, or finished_parsing.
      // Once the script is completely loaded, even if the milestones delaying
      // execution aren't removed, we eventually want to trigger
      // script-execution anyway for compatibility reasons, since waiting too
      // long for the milestones can cause compatibility issues.
      // |pending_script| has to be wrapped by WrapWeakPersistent because the
      // following delayed task should not persist a PendingScript.
      task_runner_->PostDelayedTask(
          FROM_HERE,
          WTF::BindOnce(&ScriptRunner::RemoveDelayReasonFromScript,
                        WrapWeakPersistent(this),
                        WrapWeakPersistent(pending_script),
                        DelayReason::kMilestone),
          delay_limit);
    }
    // Still to be delayed.
    return;
  }

  // Script is really ready to evaluate.
  pending_async_scripts_.erase(it);
  base::OnceClosure task = WTF::BindOnce(
      &ScriptRunner::ExecuteAsyncPendingScript, WrapWeakPersistent(this),
      WrapPersistent(pending_script), base::TimeTicks::Now());
  if (pending_script->IsEligibleForLowPriorityAsyncScriptExecution()) {
    PostTaskWithLowPriorityUntilTimeout(
        FROM_HERE, std::move(task),
        features::kTimeoutForLowPriorityAsyncScriptExecution.Get(),
        low_priority_task_runner_, task_runner_);
  } else {
    task_runner_->PostTask(FROM_HERE, std::move(task));
  }
}

void ScriptRunner::ExecuteAsyncPendingScript(
    PendingScript* pending_script,
    base::TimeTicks ready_to_evaluate_time) {
  base::UmaHistogramMediumTimes(
      "Blink.Script.AsyncScript.FromReadyToStartExecution.Time",
      base::TimeTicks::Now() - ready_to_evaluate_time);
  ExecutePendingScript(pending_script);
}

void ScriptRunner::ExecuteForceInOrderPendingScript(
    PendingScript* pending_script) {
  DCHECK_GT(pending_force_in_order_scripts_count_, 0u);
  ExecutePendingScript(pending_script);
  pending_force_in_order_scripts_count_ -= 1;
}

void ScriptRunner::ExecuteParserBlockingScriptsBlockedByForceInOrder() {
  ScriptableDocumentParser* parser = document_->GetScriptableDocumentParser();
  if (parser && document_->IsScriptExecutionReady()) {
    parser->ExecuteScriptsWaitingForResources();
  }
}

void ScriptRunner::PendingScriptFinished(PendingScript* pending_script) {
  pending_script->StopWatchingForLoad();

  switch (pending_script->GetSchedulingType()) {
    case ScriptSchedulingType::kAsync:
      CHECK(pending_async_scripts_.Contains(pending_script));
      RemoveDelayReasonFromScript(pending_script, DelayReason::kLoad);
      break;

    case ScriptSchedulingType::kInOrder:
      while (!pending_in_order_scripts_.empty() &&
             pending_in_order_scripts_.front()->IsReady()) {
        PendingScript* pending_in_order = pending_in_order_scripts_.TakeFirst();
        task_runner_->PostTask(
            FROM_HERE, WTF::BindOnce(&ScriptRunner::ExecutePendingScript,
                                     WrapWeakPersistent(this),
                                     WrapPersistent(pending_in_order)));
      }
      break;

    case ScriptSchedulingType::kForceInOrder:
      while (!pending_force_in_order_scripts_.empty() &&
             pending_force_in_order_scripts_.front()->IsReady()) {
        PendingScript* pending_in_order =
            pending_force_in_order_scripts_.TakeFirst();
        task_runner_->PostTask(
            FROM_HERE,
            WTF::BindOnce(&ScriptRunner::ExecuteForceInOrderPendingScript,
                          WrapWeakPersistent(this),
                          WrapPersistent(pending_in_order)));
      }
      if (pending_force_in_order_scripts_.empty()) {
        task_runner_->PostTask(
            FROM_HERE,
            WTF::BindOnce(&ScriptRunner::
                              ExecuteParserBlockingScriptsBlockedByForceInOrder,
                          WrapWeakPersistent(this)));
      }
      break;

    default:
      NOTREACHED();
  }
}

void ScriptRunner::ExecutePendingScript(PendingScript* pending_script) {
  TRACE_EVENT("blink", "ScriptRunner::ExecutePendingScript");

  DCHECK(!document_->domWindow() || !document_->domWindow()->IsContextPaused());
  DCHECK(pending_script);

  pending_script->ExecuteScriptBlock();

  document_->DecrementLoadEventDelayCount();
}

void ScriptRunner::Trace(Visitor* visitor) const {
  visitor->Trace(document_);
  visitor->Trace(pending_in_order_scripts_);
  visitor->Trace(pending_async_scripts_);
  visitor->Trace(pending_force_in_order_scripts_);
  PendingScriptClient::Trace(visitor);
}

ScriptRunnerDelayer::ScriptRunnerDelayer(ScriptRunner* script_runner,
                                         ScriptRunner::DelayReason delay_reason)
    : script_runner_(script_runner), delay_reason_(delay_reason) {}

void ScriptRunnerDelayer::Activate() {
  if (activated_)
    return;
  activated_ = true;
  if (script_runner_)
    script_runner_->AddDelayReason(delay_reason_);
}

void ScriptRunnerDelayer::Deactivate() {
  if (!activated_)
    return;
  activated_ = false;
  if (script_runner_)
    script_runner_->RemoveDelayReason(delay_reason_);
}

void ScriptRunnerDelayer::Trace(Visitor* visitor) const {
  visitor->Trace(script_runner_);
}

}  // namespace blink