summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/bindings/core/v8/v8_script_runner_test.cc
blob: d9d550eed554f7d3d891ac87900f505e7d087144 (plain)
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
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/bindings/core/v8/v8_script_runner.h"

#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/bindings/core/v8/referrer_script_info.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_code_cache.h"
#include "third_party/blink/renderer/core/loader/resource/script_resource.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h"
#include "third_party/blink/renderer/platform/loader/fetch/script_cached_metadata_handler.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
#include "v8/include/v8.h"

namespace blink {

namespace {

class V8ScriptRunnerTest : public testing::Test {
 public:
  V8ScriptRunnerTest() = default;
  ~V8ScriptRunnerTest() override = default;

  void SetUp() override {
    // To trick various layers of caching, increment a counter for each
    // test and use it in Code() and Url().
    counter_++;
  }

  WTF::String Code() const {
    // Simple function for testing. Note:
    // - Add counter to trick V8 code cache.
    // - Pad counter to 1000 digits, to trick minimal cacheability threshold.
    return WTF::String::Format("a = function() { 1 + 1; } // %01000d\n",
                               counter_);
  }
  KURL Url() const {
    return KURL(WTF::String::Format("http://bla.com/bla%d", counter_));
  }
  unsigned TagForCodeCache(SingleCachedMetadataHandler* cache_handler) const {
    return V8CodeCache::TagForCodeCache(cache_handler);
  }
  unsigned TagForTimeStamp(SingleCachedMetadataHandler* cache_handler) const {
    return V8CodeCache::TagForTimeStamp(cache_handler);
  }
  void SetCacheTimeStamp(SingleCachedMetadataHandler* cache_handler) {
    V8CodeCache::SetCacheTimeStamp(cache_handler);
  }

  bool CompileScript(v8::Isolate* isolate,
                     ScriptState* script_state,
                     const ScriptSourceCode& source_code,
                     mojom::blink::V8CacheOptions cache_options) {
    v8::ScriptCompiler::CompileOptions compile_options;
    V8CodeCache::ProduceCacheOptions produce_cache_options;
    v8::ScriptCompiler::NoCacheReason no_cache_reason;
    std::tie(compile_options, produce_cache_options, no_cache_reason) =
        V8CodeCache::GetCompileOptions(cache_options, source_code);
    v8::MaybeLocal<v8::Script> compiled_script = V8ScriptRunner::CompileScript(
        script_state, source_code, SanitizeScriptErrors::kSanitize,
        compile_options, no_cache_reason, ReferrerScriptInfo());
    if (compiled_script.IsEmpty()) {
      return false;
    }
    V8CodeCache::ProduceCache(isolate, compiled_script.ToLocalChecked(),
                              source_code, produce_cache_options);
    return true;
  }

  bool CompileScript(v8::Isolate* isolate,
                     ScriptState* script_state,
                     const ScriptSourceCode& source_code,
                     v8::ScriptCompiler::CompileOptions compile_options,
                     v8::ScriptCompiler::NoCacheReason no_cache_reason,
                     V8CodeCache::ProduceCacheOptions produce_cache_options) {
    v8::MaybeLocal<v8::Script> compiled_script = V8ScriptRunner::CompileScript(
        script_state, source_code, SanitizeScriptErrors::kSanitize,
        compile_options, no_cache_reason, ReferrerScriptInfo());
    if (compiled_script.IsEmpty()) {
      return false;
    }
    V8CodeCache::ProduceCache(isolate, compiled_script.ToLocalChecked(),
                              source_code, produce_cache_options);
    return true;
  }

  ScriptResource* CreateEmptyResource() {
    ScriptResource* resource =
        ScriptResource::CreateForTest(NullURL(), UTF8Encoding());
    return resource;
  }

  ScriptResource* CreateResource(const WTF::TextEncoding& encoding) {
    ScriptResource* resource = ScriptResource::CreateForTest(Url(), encoding);
    String code = Code();
    ResourceResponse response(Url());
    response.SetHttpStatusCode(200);
    resource->SetResponse(response);
    StringUTF8Adaptor code_utf8(code);
    resource->AppendData(code_utf8.data(), code_utf8.size());
    resource->FinishForTest();
    return resource;
  }

 protected:
  static int counter_;
  base::test::ScopedFeatureList feature_list_;
};

int V8ScriptRunnerTest::counter_ = 0;

class HistogramCounter {
 public:
  explicit HistogramCounter(const base::HistogramTester& tester)
      : tester_(tester) {}

  int32_t GetTotal() { return GetSamples()->TotalCount(); }

  int32_t GetPresent() { return GetCount(StateOnGet::kPresent); }

  int32_t GetDataTypeMismatch() {
    return GetCount(StateOnGet::kDataTypeMismatch);
  }

  int32_t GetWasNeverPresent() {
    return GetCount(StateOnGet::kWasNeverPresent);
  }

  int32_t GetDiscarded() { return GetCount(StateOnGet::kWasDiscarded); }

 private:
  std::unique_ptr<base::HistogramSamples> GetSamples() {
    return tester_.GetHistogramSamplesSinceCreation(
        "Memory.Renderer.BlinkCachedMetadataGetResult");
  }

  int32_t GetCount(StateOnGet state) {
    static_assert((std::is_same<int, base::HistogramBase::Sample>::value), "");
    return GetSamples()->GetCount(static_cast<int>(state));
  }

  const base::HistogramTester& tester_;
};

TEST_F(V8ScriptRunnerTest, resourcelessShouldPass) {
  V8TestingScope scope;
  ScriptSourceCode source_code(Code(), ScriptSourceLocationType::kInternal,
                               nullptr /* cache_handler */, Url());
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, mojom::blink::V8CacheOptions::kNone));
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, mojom::blink::V8CacheOptions::kCode));
}

TEST_F(V8ScriptRunnerTest, emptyResourceDoesNotHaveCacheHandler) {
  ScriptResource* resource = CreateEmptyResource();
  EXPECT_FALSE(resource->CacheHandler());
}

TEST_F(V8ScriptRunnerTest, codeOption) {
  V8TestingScope scope;
  ScriptSourceCode source_code(
      nullptr, CreateResource(UTF8Encoding()),
      ScriptStreamer::NotStreamingReason::kScriptTooSmall);
  SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler();
  SetCacheTimeStamp(cache_handler);

  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, mojom::blink::V8CacheOptions::kCode));

  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));
  // The cached data is associated with the encoding.
  ScriptResource* another_resource =
      CreateResource(UTF16LittleEndianEncoding());
  EXPECT_FALSE(cache_handler->GetCachedMetadata(
      TagForCodeCache(another_resource->CacheHandler())));
}

TEST_F(V8ScriptRunnerTest, consumeCodeOptionWithoutDiscarding) {
  feature_list_.InitAndDisableFeature(
      blink::features::kDiscardCodeCacheAfterFirstUse);
  V8TestingScope scope;
  ScriptSourceCode source_code(
      nullptr, CreateResource(UTF8Encoding()),
      ScriptStreamer::NotStreamingReason::kScriptTooSmall);
  // Set timestamp to simulate a warm run.
  SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler();
  SetCacheTimeStamp(cache_handler);

  // Warm run - should produce code cache.
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, mojom::blink::V8CacheOptions::kCode));

  // Check the produced cache is for code cache.
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));

  // Hot run - should consume code cache.
  v8::ScriptCompiler::CompileOptions compile_options;
  V8CodeCache::ProduceCacheOptions produce_cache_options;
  v8::ScriptCompiler::NoCacheReason no_cache_reason;
  std::tie(compile_options, produce_cache_options, no_cache_reason) =
      V8CodeCache::GetCompileOptions(mojom::blink::V8CacheOptions::kDefault,
                                     source_code);
  EXPECT_EQ(produce_cache_options,
            V8CodeCache::ProduceCacheOptions::kNoProduceCache);
  EXPECT_EQ(compile_options,
            v8::ScriptCompiler::CompileOptions::kConsumeCodeCache);
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, compile_options, no_cache_reason,
                            produce_cache_options));
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));
}

TEST_F(V8ScriptRunnerTest, consumeCodeOptionWithDiscarding) {
  feature_list_.InitAndEnableFeature(
      blink::features::kDiscardCodeCacheAfterFirstUse);
  V8TestingScope scope;
  ScriptSourceCode source_code(
      nullptr, CreateResource(UTF8Encoding()),
      ScriptStreamer::NotStreamingReason::kScriptTooSmall);
  // Set timestamp to simulate a warm run.
  SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler();
  SetCacheTimeStamp(cache_handler);

  // Warm run - should produce code cache.
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, mojom::blink::V8CacheOptions::kCode));

  // Check the produced cache is for code cache.
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));

  // Hot run - should consume code cache.
  base::HistogramTester tester;
  HistogramCounter counter(tester);
  v8::ScriptCompiler::CompileOptions compile_options;
  V8CodeCache::ProduceCacheOptions produce_cache_options;
  v8::ScriptCompiler::NoCacheReason no_cache_reason;
  std::tie(compile_options, produce_cache_options, no_cache_reason) =
      V8CodeCache::GetCompileOptions(mojom::blink::V8CacheOptions::kDefault,
                                     source_code);
  EXPECT_EQ(1, counter.GetTotal());
  EXPECT_EQ(1, counter.GetPresent());
  EXPECT_EQ(produce_cache_options,
            V8CodeCache::ProduceCacheOptions::kNoProduceCache);
  EXPECT_EQ(compile_options,
            v8::ScriptCompiler::CompileOptions::kConsumeCodeCache);
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, compile_options, no_cache_reason,
                            produce_cache_options));
  EXPECT_EQ(2, counter.GetTotal());
  EXPECT_EQ(2, counter.GetPresent());
  EXPECT_FALSE(
      cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));
  EXPECT_EQ(3, counter.GetTotal());
  EXPECT_EQ(1, counter.GetDiscarded());
}

TEST_F(V8ScriptRunnerTest, produceAndConsumeCodeOptionWithoutDiscarding) {
  feature_list_.InitAndDisableFeature(
      blink::features::kDiscardCodeCacheAfterFirstUse);
  V8TestingScope scope;
  ScriptSourceCode source_code(
      nullptr, CreateResource(UTF8Encoding()),
      ScriptStreamer::NotStreamingReason::kScriptTooSmall);
  SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler();

  // Cold run - should set the timestamp.
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code,
                            mojom::blink::V8CacheOptions::kDefault));
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForTimeStamp(cache_handler)));
  EXPECT_FALSE(
      cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));

  // Warm run - should produce code cache.
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code,
                            mojom::blink::V8CacheOptions::kDefault));
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));

  // Hot run - should consume code cache.
  v8::ScriptCompiler::CompileOptions compile_options;
  V8CodeCache::ProduceCacheOptions produce_cache_options;
  v8::ScriptCompiler::NoCacheReason no_cache_reason;
  std::tie(compile_options, produce_cache_options, no_cache_reason) =
      V8CodeCache::GetCompileOptions(mojom::blink::V8CacheOptions::kDefault,
                                     source_code);
  EXPECT_EQ(produce_cache_options,
            V8CodeCache::ProduceCacheOptions::kNoProduceCache);
  EXPECT_EQ(compile_options,
            v8::ScriptCompiler::CompileOptions::kConsumeCodeCache);
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, compile_options, no_cache_reason,
                            produce_cache_options));
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));
}

TEST_F(V8ScriptRunnerTest, produceAndConsumeCodeOptionWithDiscarding) {
  feature_list_.InitAndEnableFeature(
      blink::features::kDiscardCodeCacheAfterFirstUse);
  V8TestingScope scope;
  ScriptSourceCode source_code(
      nullptr, CreateResource(UTF8Encoding()),
      ScriptStreamer::NotStreamingReason::kScriptTooSmall);
  SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler();

  // Cold run - should set the timestamp.
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code,
                            mojom::blink::V8CacheOptions::kDefault));
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForTimeStamp(cache_handler)));
  EXPECT_FALSE(
      cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));

  // Warm run - should produce code cache.
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code,
                            mojom::blink::V8CacheOptions::kDefault));
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));

  // Hot run - should consume code cache.
  v8::ScriptCompiler::CompileOptions compile_options;
  V8CodeCache::ProduceCacheOptions produce_cache_options;
  v8::ScriptCompiler::NoCacheReason no_cache_reason;
  std::tie(compile_options, produce_cache_options, no_cache_reason) =
      V8CodeCache::GetCompileOptions(mojom::blink::V8CacheOptions::kDefault,
                                     source_code);
  EXPECT_EQ(produce_cache_options,
            V8CodeCache::ProduceCacheOptions::kNoProduceCache);
  EXPECT_EQ(compile_options,
            v8::ScriptCompiler::CompileOptions::kConsumeCodeCache);
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code, compile_options, no_cache_reason,
                            produce_cache_options));
  EXPECT_FALSE(
      cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));
}

TEST_F(V8ScriptRunnerTest, cacheRequestedBeforeProduced) {
  feature_list_.InitAndEnableFeature(
      blink::features::kDiscardCodeCacheAfterFirstUse);
  V8TestingScope scope;
  ScriptSourceCode source_code(
      nullptr, CreateResource(UTF8Encoding()),
      ScriptStreamer::NotStreamingReason::kScriptTooSmall);
  SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler();
  base::HistogramTester tester;
  HistogramCounter counter(tester);
  EXPECT_FALSE(
      cache_handler->GetCachedMetadata(TagForTimeStamp(cache_handler)));
  EXPECT_EQ(1, counter.GetTotal());
  EXPECT_EQ(1, counter.GetWasNeverPresent());
}

TEST_F(V8ScriptRunnerTest, cacheDataTypeMismatch) {
  feature_list_.InitAndEnableFeature(
      blink::features::kDiscardCodeCacheAfterFirstUse);
  V8TestingScope scope;
  ScriptSourceCode source_code(
      nullptr, CreateResource(UTF8Encoding()),
      ScriptStreamer::NotStreamingReason::kScriptTooSmall);
  SingleCachedMetadataHandler* cache_handler = source_code.CacheHandler();
  EXPECT_FALSE(
      cache_handler->GetCachedMetadata(TagForTimeStamp(cache_handler)));
  EXPECT_TRUE(CompileScript(scope.GetIsolate(), scope.GetScriptState(),
                            source_code,
                            mojom::blink::V8CacheOptions::kDefault));
  EXPECT_TRUE(cache_handler->GetCachedMetadata(TagForTimeStamp(cache_handler)));
  base::HistogramTester tester;
  HistogramCounter counter(tester);
  EXPECT_FALSE(
      cache_handler->GetCachedMetadata(TagForCodeCache(cache_handler)));
  EXPECT_EQ(1, counter.GetTotal());
  EXPECT_EQ(1, counter.GetDataTypeMismatch());
}

}  // namespace

}  // namespace blink