summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/platform/bindings/script_forbidden_scope.h
blob: 656083c7377d67e07f668a36699da62dc0e2e719 (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
// 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.

#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_SCRIPT_FORBIDDEN_SCOPE_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_SCRIPT_FORBIDDEN_SCOPE_H_

#include "base/auto_reset.h"
#include "base/macros.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/stack_util.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"

namespace blink {

// Scoped disabling of script execution.
class PLATFORM_EXPORT ScriptForbiddenScope final {
  STACK_ALLOCATED();
  DISALLOW_COPY_AND_ASSIGN(ScriptForbiddenScope);

 public:
  ScriptForbiddenScope() { Enter(); }
  ~ScriptForbiddenScope() { Exit(); }

  class PLATFORM_EXPORT AllowUserAgentScript final {
    STACK_ALLOCATED();
    DISALLOW_COPY_AND_ASSIGN(AllowUserAgentScript);

   public:
    AllowUserAgentScript() : saved_counter_(&GetMutableCounter(), 0) {}
    ~AllowUserAgentScript() { DCHECK(!IsScriptForbidden()); }

   private:
    base::AutoReset<unsigned> saved_counter_;
  };

  static bool IsScriptForbidden() {
    if (LIKELY(!WTF::MayNotBeMainThread()))
      return g_main_thread_counter_ > 0;
    return GetMutableCounter() > 0;
  }

  // DO NOT USE THESE FUNCTIONS FROM OUTSIDE OF THIS CLASS.
  static void Enter() {
    if (LIKELY(!WTF::MayNotBeMainThread())) {
      ++g_main_thread_counter_;
    } else {
      ++GetMutableCounter();
    }
  }
  static void Exit() {
    DCHECK(IsScriptForbidden());
    if (LIKELY(!WTF::MayNotBeMainThread())) {
      --g_main_thread_counter_;
    } else {
      --GetMutableCounter();
    }
  }

 private:
  static unsigned& GetMutableCounter();
  static unsigned g_main_thread_counter_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_BINDINGS_SCRIPT_FORBIDDEN_SCOPE_H_