1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
6
7 #ifndef mozilla_SafeMode_h
8 #define mozilla_SafeMode_h
9
10 // NB: This code must be able to run apart from XPCOM
11
12 #include "mozilla/CmdLineAndEnvUtils.h"
13 #include "mozilla/Maybe.h"
14
15 #if defined(XP_WIN)
16 # include "mozilla/PolicyChecks.h"
17 # include <windows.h>
18 #endif // defined(XP_WIN)
19
20 // Undo X11/X.h's definition of None
21 #undef None
22
23 namespace mozilla {
24
25 enum class SafeModeFlag : uint32_t {
26 None = 0,
27 Unset = (1 << 0),
28 NoKeyPressCheck = (1 << 1),
29 };
30
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(SafeModeFlag)31 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(SafeModeFlag)
32
33 template <typename CharT>
34 inline Maybe<bool> IsSafeModeRequested(
35 int& aArgc, CharT* aArgv[],
36 const SafeModeFlag aFlags = SafeModeFlag::Unset) {
37 CheckArgFlag checkArgFlags = CheckArgFlag::None;
38 if (aFlags & SafeModeFlag::Unset) {
39 checkArgFlags |= CheckArgFlag::RemoveArg;
40 }
41
42 ArgResult ar =
43 CheckArg(aArgc, aArgv, GetLiteral<CharT, FlagLiteral::safemode>(),
44 static_cast<const CharT**>(nullptr), checkArgFlags);
45 if (ar == ARG_BAD) {
46 return Nothing();
47 }
48
49 bool result = ar == ARG_FOUND;
50
51 #if defined(XP_WIN)
52 // If the shift key is pressed and the ctrl and / or alt keys are not pressed
53 // during startup, start in safe mode. GetKeyState returns a short and the
54 // high order bit will be 1 if the key is pressed. By masking the returned
55 // short with 0x8000 the result will be 0 if the key is not pressed and
56 // non-zero otherwise.
57 if (!(aFlags & SafeModeFlag::NoKeyPressCheck) &&
58 (GetKeyState(VK_SHIFT) & 0x8000) && !(GetKeyState(VK_CONTROL) & 0x8000) &&
59 !(GetKeyState(VK_MENU) & 0x8000) &&
60 !EnvHasValue("MOZ_DISABLE_SAFE_MODE_KEY")) {
61 result = true;
62 }
63
64 if (result && PolicyCheckBoolean(L"DisableSafeMode")) {
65 result = false;
66 }
67 #endif // defined(XP_WIN)
68
69 #if defined(XP_MACOSX)
70 if (!(aFlags & SafeModeFlag::NoKeyPressCheck) &&
71 (GetCurrentEventKeyModifiers() & optionKey) &&
72 !EnvHasValue("MOZ_DISABLE_SAFE_MODE_KEY")) {
73 result = true;
74 }
75 #endif // defined(XP_MACOSX)
76
77 // The Safe Mode Policy should not be enforced for the env var case
78 // (used by updater and crash-recovery).
79 if (EnvHasValue("MOZ_SAFE_MODE_RESTART")) {
80 result = true;
81 if (aFlags & SafeModeFlag::Unset) {
82 // unset the env variable
83 SaveToEnv("MOZ_SAFE_MODE_RESTART=");
84 }
85 }
86
87 return Some(result);
88 }
89
90 } // namespace mozilla
91
92 #endif // mozilla_SafeMode_h
93