DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (409f3966645a)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ProcessRewind.h"

#include "nsString.h"
#include "ipc/ChildInternal.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/StaticMutex.h"
#include "InfallibleVector.h"
#include "MemorySnapshot.h"
#include "Monitor.h"
#include "ProcessRecordReplay.h"
#include "ThreadSnapshot.h"

namespace mozilla {
namespace recordreplay {

// Information about the current rewinding state. The contents of this structure
// are in untracked memory.
struct RewindInfo
{
  // The most recent checkpoint which was encountered.
  CheckpointId mLastCheckpoint;

  // Whether this is the active child process. See the comment under
  // 'Child Roles' in ParentIPC.cpp.
  bool mIsActiveChild;

  // Checkpoints which have been saved. This includes only entries from
  // mShouldSaveCheckpoints, plus all temporary checkpoints.
  InfallibleVector<SavedCheckpoint, 1024, AllocPolicy<MemoryKind::Generic>> mSavedCheckpoints;

  // Unsorted list of checkpoints which the middleman has instructed us to
  // save. All those equal to or prior to mLastCheckpoint will have been saved.
  InfallibleVector<size_t, 1024, AllocPolicy<MemoryKind::Generic>> mShouldSaveCheckpoints;
};

static RewindInfo* gRewindInfo;

// Lock for managing pending main thread callbacks.
static Monitor* gMainThreadCallbackMonitor;

// Callbacks to execute on the main thread, in FIFO order. Protected by
// gMainThreadCallbackMonitor.
static StaticInfallibleVector<std::function<void()>> gMainThreadCallbacks;

void
InitializeRewindState()
{
  MOZ_RELEASE_ASSERT(gRewindInfo == nullptr);
  void* memory = AllocateMemory(sizeof(RewindInfo), MemoryKind::Generic);
  gRewindInfo = new(memory) RewindInfo();

  gMainThreadCallbackMonitor = new Monitor();
}

static bool
CheckpointPrecedes(const CheckpointId& aFirst, const CheckpointId& aSecond)
{
  return aFirst.mNormal < aSecond.mNormal || aFirst.mTemporary < aSecond.mTemporary;
}

void
RestoreCheckpointAndResume(const CheckpointId& aCheckpoint)
{
  MOZ_RELEASE_ASSERT(IsReplaying());
  MOZ_RELEASE_ASSERT(Thread::CurrentIsMainThread());
  MOZ_RELEASE_ASSERT(!AreThreadEventsPassedThrough());
  MOZ_RELEASE_ASSERT(aCheckpoint == gRewindInfo->mLastCheckpoint ||
                     CheckpointPrecedes(aCheckpoint, gRewindInfo->mLastCheckpoint));

  // Make sure we don't lose pending main thread callbacks due to rewinding.
  {
    MonitorAutoLock lock(*gMainThreadCallbackMonitor);
    MOZ_RELEASE_ASSERT(gMainThreadCallbacks.empty());
  }

  Thread::WaitForIdleThreads();

  double start = CurrentTime();

  {
    // Rewind heap memory to the target checkpoint, which must have been saved.
    AutoDisallowMemoryChanges disallow;
    CheckpointId newCheckpoint = gRewindInfo->mSavedCheckpoints.back().mCheckpoint;
    RestoreMemoryToLastSavedCheckpoint();
    while (CheckpointPrecedes(aCheckpoint, newCheckpoint)) {
      gRewindInfo->mSavedCheckpoints.back().ReleaseContents();
      gRewindInfo->mSavedCheckpoints.popBack();
      RestoreMemoryToLastSavedDiffCheckpoint();
      newCheckpoint = gRewindInfo->mSavedCheckpoints.back().mCheckpoint;
    }
    MOZ_RELEASE_ASSERT(newCheckpoint == aCheckpoint);
  }

  FixupFreeRegionsAfterRewind();

  double end = CurrentTime();
  PrintSpew("Restore #%d:%d -> #%d:%d %.2fs\n",
            (int) gRewindInfo->mLastCheckpoint.mNormal,
            (int) gRewindInfo->mLastCheckpoint.mTemporary,
            (int) aCheckpoint.mNormal,
            (int) aCheckpoint.mTemporary,
            (end - start) / 1000000.0);

  // Finally, let threads restore themselves to their stacks at the checkpoint
  // we are rewinding to.
  RestoreAllThreads(gRewindInfo->mSavedCheckpoints.back());
  Unreachable();
}

void
SetSaveCheckpoint(size_t aCheckpoint, bool aSave)
{
  MOZ_RELEASE_ASSERT(aCheckpoint > gRewindInfo->mLastCheckpoint.mNormal);
  VectorAddOrRemoveEntry(gRewindInfo->mShouldSaveCheckpoints, aCheckpoint, aSave);
}

bool
NewCheckpoint(bool aTemporary)
{
  MOZ_RELEASE_ASSERT(Thread::CurrentIsMainThread());
  MOZ_RELEASE_ASSERT(!AreThreadEventsPassedThrough());
  MOZ_RELEASE_ASSERT(IsReplaying() || !aTemporary);

  navigation::BeforeCheckpoint();

  // Get the ID of the new checkpoint.
  CheckpointId checkpoint = gRewindInfo->mLastCheckpoint.NextCheckpoint(aTemporary);

  // Save all checkpoints the middleman tells us to, and temporary checkpoints
  // (which the middleman never knows about).
  bool save = aTemporary
           || VectorContains(gRewindInfo->mShouldSaveCheckpoints, checkpoint.mNormal);
  bool reachedCheckpoint = true;

  if (save) {
    Thread::WaitForIdleThreads();

    PrintSpew("Starting checkpoint...\n");

    double start = CurrentTime();

    // Record either the first or a subsequent diff memory snapshot.
    if (gRewindInfo->mSavedCheckpoints.empty()) {
      TakeFirstMemorySnapshot();
    } else {
      TakeDiffMemorySnapshot();
    }
    gRewindInfo->mSavedCheckpoints.emplaceBack(checkpoint);

    double end = CurrentTime();

    // Save all thread stacks for the checkpoint. If we rewind here from a
    // later point of execution then this will return false.
    if (SaveAllThreads(gRewindInfo->mSavedCheckpoints.back())) {
      PrintSpew("Saved checkpoint #%d:%d %.2fs\n",
                (int) checkpoint.mNormal, (int) checkpoint.mTemporary,
                (end - start) / 1000000.0);
    } else {
      PrintSpew("Restored checkpoint #%d:%d\n",
                (int) checkpoint.mNormal, (int) checkpoint.mTemporary);

      reachedCheckpoint = false;

      // After restoring, make sure all threads have updated their stacks
      // before letting any of them resume execution. Threads might have
      // pointers into each others' stacks.
      WaitForIdleThreadsToRestoreTheirStacks();
    }

    Thread::ResumeIdleThreads();
  }

  gRewindInfo->mLastCheckpoint = checkpoint;

  navigation::AfterCheckpoint(checkpoint);

  return reachedCheckpoint;
}

static bool gRecordingDiverged;
static bool gUnhandledDivergeAllowed;

void
DivergeFromRecording()
{
  MOZ_RELEASE_ASSERT(Thread::CurrentIsMainThread());
  MOZ_RELEASE_ASSERT(IsReplaying());
  gRecordingDiverged = true;
  gUnhandledDivergeAllowed = true;
}

extern "C" {

MOZ_EXPORT bool
RecordReplayInterface_InternalHasDivergedFromRecording()
{
  return Thread::CurrentIsMainThread() && gRecordingDiverged;
}

} // extern "C"

void
DisallowUnhandledDivergeFromRecording()
{
  MOZ_RELEASE_ASSERT(Thread::CurrentIsMainThread());
  gUnhandledDivergeAllowed = false;
}

void
EnsureNotDivergedFromRecording()
{
  MOZ_RELEASE_ASSERT(!AreThreadEventsPassedThrough());
  if (HasDivergedFromRecording()) {
    MOZ_RELEASE_ASSERT(gUnhandledDivergeAllowed);
    PrintSpew("Unhandled recording divergence, restoring checkpoint...\n");
    RestoreCheckpointAndResume(gRewindInfo->mSavedCheckpoints.back().mCheckpoint);
    Unreachable();
  }
}

bool
HasSavedCheckpoint()
{
  return gRewindInfo && !gRewindInfo->mSavedCheckpoints.empty();
}

CheckpointId
GetLastSavedCheckpoint()
{
  MOZ_RELEASE_ASSERT(HasSavedCheckpoint());
  return gRewindInfo->mSavedCheckpoints.back().mCheckpoint;
}

static bool gMainThreadShouldPause = false;

bool
MainThreadShouldPause()
{
  return gMainThreadShouldPause;
}

void
PauseMainThreadAndServiceCallbacks()
{
  MOZ_RELEASE_ASSERT(Thread::CurrentIsMainThread());
  MOZ_RELEASE_ASSERT(!AreThreadEventsPassedThrough());
  MOZ_RELEASE_ASSERT(!gRecordingDiverged);

  // Whether there is a PauseMainThreadAndServiceCallbacks frame on the stack.
  static bool gMainThreadIsPaused = false;

  if (gMainThreadIsPaused) {
    return;
  }
  gMainThreadIsPaused = true;

  MonitorAutoLock lock(*gMainThreadCallbackMonitor);

  // Loop and invoke callbacks until one of them unpauses this thread.
  while (gMainThreadShouldPause) {
    if (!gMainThreadCallbacks.empty()) {
      std::function<void()> callback = gMainThreadCallbacks[0];
      gMainThreadCallbacks.erase(&gMainThreadCallbacks[0]);
      {
        MonitorAutoUnlock unlock(*gMainThreadCallbackMonitor);
        AutoDisallowThreadEvents disallow;
        callback();
      }
    } else {
      gMainThreadCallbackMonitor->Wait();
    }
  }

  // As for RestoreCheckpointAndResume, we shouldn't resume the main thread while
  // it still has callbacks to execute.
  MOZ_RELEASE_ASSERT(gMainThreadCallbacks.empty());

  // If we diverge from the recording the only way we can get back to resuming
  // normal execution is to rewind to a checkpoint prior to the divergence.
  MOZ_RELEASE_ASSERT(!gRecordingDiverged);

  gMainThreadIsPaused = false;
}

void
PauseMainThreadAndInvokeCallback(const std::function<void()>& aCallback)
{
  {
    MonitorAutoLock lock(*gMainThreadCallbackMonitor);
    gMainThreadShouldPause = true;
    gMainThreadCallbacks.append(aCallback);
    gMainThreadCallbackMonitor->Notify();
  }

  if (Thread::CurrentIsMainThread()) {
    PauseMainThreadAndServiceCallbacks();
  }
}

void
ResumeExecution()
{
  MonitorAutoLock lock(*gMainThreadCallbackMonitor);
  gMainThreadShouldPause = false;
  gMainThreadCallbackMonitor->Notify();
}

void
SetIsActiveChild(bool aActive)
{
  gRewindInfo->mIsActiveChild = aActive;
}

bool
IsActiveChild()
{
  return gRewindInfo->mIsActiveChild;
}

} // namespace recordreplay
} // namespace mozilla