Hash :
0757254b
        
        Author :
  
        
        Date :
2024-11-22T10:21:29
        
      
Tests: Add crash callback to test Replay (e.g. linux-trace) Prints a backtrace on trapped signals. Didn't help with the issue on the bug as it was an OOM -> SIGKILL which can't be trapped but generally nice to have. Also adds stdout flushes to the signal handler as stdout redirection is by default _not_ line-buffered, so without a flush the printfs just go into the buffer and don't actually show up in the redirected output (including on bots). This might be the reason we were missing backtraces in some other cases. Bug: angleproject:380296979 Change-Id: I9fbba35e3bf4e6d863139ceb533f51973fe2f98d Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/6044040 Commit-Queue: Shahbaz Youssefi <syoussefi@chromium.org> Reviewed-by: Shahbaz Youssefi <syoussefi@chromium.org>
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 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
//
// Copyright 2020 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// CaptureReplayTest.cpp:
//   Application that runs replay for testing of capture replay
//
#include "common/debug.h"
#include "common/system_utils.h"
#include "platform/PlatformMethods.h"
#include "traces_export.h"
#include "util/EGLPlatformParameters.h"
#include "util/EGLWindow.h"
#include "util/OSWindow.h"
#include "util/shader_utils.h"
#include "util/test_utils.h"
#if defined(ANGLE_PLATFORM_ANDROID)
#    include "util/android/AndroidWindow.h"
#endif
#include <stdint.h>
#include <string.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <list>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include "frame_capture_test_utils.h"
namespace
{
EGLWindow *gEGLWindow                = nullptr;
constexpr char kResultTag[]          = "*RESULT";
constexpr int kInitializationFailure = -1;
constexpr int kSerializationFailure  = -2;
constexpr int kExitSuccess           = 0;
// This arbitrary value rejects placeholder serialized states. In practice they are many thousands
// of characters long. See frame_capture_utils_mock.cpp for the current placeholder string.
constexpr size_t kTooShortStateLength = 40;
[[maybe_unused]] bool IsGLExtensionEnabled(const std::string &extName)
{
    return angle::CheckExtensionExists(reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)),
                                       extName);
}
[[maybe_unused]] void KHRONOS_APIENTRY DebugCallback(GLenum source,
                                                     GLenum type,
                                                     GLuint id,
                                                     GLenum severity,
                                                     GLsizei length,
                                                     const GLchar *message,
                                                     const void *userParam)
{
    printf("%s\n", message);
}
[[maybe_unused]] void LogError(angle::PlatformMethods *platform, const char *errorMessage)
{
    printf("ERR: %s\n", errorMessage);
}
[[maybe_unused]] void LogWarning(angle::PlatformMethods *platform, const char *warningMessage)
{
    printf("WARN: %s\n", warningMessage);
}
[[maybe_unused]] void LogInfo(angle::PlatformMethods *platform, const char *infoMessage)
{
    printf("INFO: %s\n", infoMessage);
}
bool CompareSerializedContexts(const char *capturedSerializedContextState,
                               const char *replaySerializedContextState)
{
    return strcmp(replaySerializedContextState, capturedSerializedContextState) == 0;
}
EGLImage KHRONOS_APIENTRY EGLCreateImage(EGLDisplay display,
                                         EGLContext context,
                                         EGLenum target,
                                         EGLClientBuffer buffer,
                                         const EGLAttrib *attrib_list)
{
    GLWindowContext ctx = reinterpret_cast<GLWindowContext>(context);
    return gEGLWindow->createImage(ctx, target, buffer, attrib_list);
}
EGLImage KHRONOS_APIENTRY EGLCreateImageKHR(EGLDisplay display,
                                            EGLContext context,
                                            EGLenum target,
                                            EGLClientBuffer buffer,
                                            const EGLint *attrib_list)
{
    GLWindowContext ctx = reinterpret_cast<GLWindowContext>(context);
    return gEGLWindow->createImageKHR(ctx, target, buffer, attrib_list);
}
EGLBoolean KHRONOS_APIENTRY EGLDestroyImage(EGLDisplay display, EGLImage image)
{
    return gEGLWindow->destroyImage(image);
}
EGLBoolean KHRONOS_APIENTRY EGLDestroyImageKHR(EGLDisplay display, EGLImage image)
{
    return gEGLWindow->destroyImageKHR(image);
}
EGLSurface KHRONOS_APIENTRY EGLCreatePbufferSurface(EGLDisplay display,
                                                    EGLConfig *config,
                                                    const EGLint *attrib_list)
{
    return gEGLWindow->createPbufferSurface(attrib_list);
}
EGLBoolean KHRONOS_APIENTRY EGLDestroySurface(EGLDisplay display, EGLSurface surface)
{
    return gEGLWindow->destroySurface(surface);
}
EGLBoolean KHRONOS_APIENTRY EGLBindTexImage(EGLDisplay display, EGLSurface surface, EGLint buffer)
{
    return gEGLWindow->bindTexImage(surface, buffer);
}
EGLBoolean KHRONOS_APIENTRY EGLReleaseTexImage(EGLDisplay display,
                                               EGLSurface surface,
                                               EGLint buffer)
{
    return gEGLWindow->releaseTexImage(surface, buffer);
}
EGLBoolean KHRONOS_APIENTRY EGLMakeCurrent(EGLDisplay display,
                                           EGLSurface draw,
                                           EGLSurface read,
                                           EGLContext context)
{
    return gEGLWindow->makeCurrent(draw, read, context);
}
}  // namespace
GenericProc KHRONOS_APIENTRY TraceLoadProc(const char *procName)
{
    if (!gEGLWindow)
    {
        std::cout << "No Window pointer in TraceLoadProc.\n";
        return nullptr;
    }
    else
    {
        if (strcmp(procName, "eglCreateImage") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLCreateImage);
        }
        if (strcmp(procName, "eglCreateImageKHR") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLCreateImageKHR);
        }
        if (strcmp(procName, "eglDestroyImage") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLDestroyImage);
        }
        if (strcmp(procName, "eglDestroyImageKHR") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLDestroyImageKHR);
        }
        if (strcmp(procName, "eglCreatePbufferSurface") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLCreatePbufferSurface);
        }
        if (strcmp(procName, "eglDestroySurface") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLDestroySurface);
        }
        if (strcmp(procName, "eglBindTexImage") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLBindTexImage);
        }
        if (strcmp(procName, "eglReleaseTexImage") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLReleaseTexImage);
        }
        if (strcmp(procName, "eglMakeCurrent") == 0)
        {
            return reinterpret_cast<GenericProc>(EGLMakeCurrent);
        }
        return gEGLWindow->getProcAddress(procName);
    }
}
class CaptureReplayTests
{
  public:
    CaptureReplayTests()
    {
        // Load EGL library so we can initialize the display.
        mEntryPointsLib.reset(
            angle::OpenSharedLibrary(ANGLE_EGL_LIBRARY_NAME, angle::SearchType::ModuleDir));
        mOSWindow = OSWindow::New();
        mOSWindow->disableErrorMessageDialog();
    }
    ~CaptureReplayTests()
    {
        EGLWindow::Delete(&mEGLWindow);
        OSWindow::Delete(&mOSWindow);
    }
    bool initializeTest(const std::string &execDir, const angle::TraceInfo &traceInfo)
    {
        if (!mOSWindow->initialize(traceInfo.name, traceInfo.drawSurfaceWidth,
                                   traceInfo.drawSurfaceHeight))
        {
            return false;
        }
        mOSWindow->disableErrorMessageDialog();
        mOSWindow->setVisible(true);
        if (mEGLWindow && !mEGLWindow->isContextVersion(traceInfo.contextClientMajorVersion,
                                                        traceInfo.contextClientMinorVersion))
        {
            EGLWindow::Delete(&mEGLWindow);
            mEGLWindow = nullptr;
        }
        if (!mEGLWindow)
        {
            mEGLWindow = EGLWindow::New(traceInfo.contextClientMajorVersion,
                                        traceInfo.contextClientMinorVersion);
        }
        ConfigParameters configParams;
        configParams.redBits     = traceInfo.configRedBits;
        configParams.greenBits   = traceInfo.configGreenBits;
        configParams.blueBits    = traceInfo.configBlueBits;
        configParams.alphaBits   = traceInfo.configAlphaBits;
        configParams.depthBits   = traceInfo.configDepthBits;
        configParams.stencilBits = traceInfo.configStencilBits;
        configParams.clientArraysEnabled   = traceInfo.areClientArraysEnabled;
        configParams.bindGeneratesResource = traceInfo.isBindGeneratesResourcesEnabled;
        configParams.webGLCompatibility    = traceInfo.isWebGLCompatibilityEnabled;
        configParams.robustResourceInit    = traceInfo.isRobustResourceInitEnabled;
        mPlatformParams.renderer   = traceInfo.displayPlatformType;
        mPlatformParams.deviceType = traceInfo.displayDeviceType;
        mPlatformParams.enable(angle::Feature::ForceInitShaderVariables);
        mPlatformParams.enable(angle::Feature::EnableCaptureLimits);
#if defined(ANGLE_ENABLE_ASSERTS)
        mPlatformMethods.logError       = LogError;
        mPlatformMethods.logWarning     = LogWarning;
        mPlatformMethods.logInfo        = LogInfo;
        mPlatformParams.platformMethods = &mPlatformMethods;
#endif  // defined(ANGLE_ENABLE_ASSERTS)
        if (!mEGLWindow->initializeGL(mOSWindow, mEntryPointsLib.get(),
                                      angle::GLESDriverType::AngleEGL, mPlatformParams,
                                      configParams))
        {
            mOSWindow->destroy();
            return false;
        }
        gEGLWindow = mEGLWindow;
        LoadTraceEGL(TraceLoadProc);
        LoadTraceGLES(TraceLoadProc);
        // Disable vsync
        if (!mEGLWindow->setSwapInterval(0))
        {
            cleanupTest();
            return false;
        }
#if defined(ANGLE_ENABLE_ASSERTS)
        if (IsGLExtensionEnabled("GL_KHR_debug"))
        {
            EnableDebugCallback(DebugCallback, nullptr);
        }
#endif
        std::string baseDir = "";
#if defined(ANGLE_TRACE_EXTERNAL_BINARIES)
        baseDir += AndroidWindow::GetApplicationDirectory() + "/angle_traces/";
#endif
        // Load trace
        mTraceLibrary.reset(new angle::TraceLibrary(traceInfo.name, traceInfo, baseDir));
        if (!mTraceLibrary->valid())
        {
            std::cout << "Failed to load trace library: " << traceInfo.name << "\n";
            return false;
        }
        std::stringstream binaryPathStream;
        binaryPathStream << execDir << angle::GetPathSeparator()
                         << ANGLE_CAPTURE_REPLAY_TEST_DATA_DIR;
        mTraceLibrary->setBinaryDataDir(binaryPathStream.str().c_str());
        mTraceLibrary->setupReplay();
        return true;
    }
    void cleanupTest()
    {
        mTraceLibrary->finishReplay();
        mTraceLibrary.reset(nullptr);
        mEGLWindow->destroyGL();
        mOSWindow->destroy();
    }
    void swap() { mEGLWindow->swap(); }
    int runTest(const std::string &exeDir, const angle::TraceInfo &traceInfo)
    {
        if (!initializeTest(exeDir, traceInfo))
        {
            return kInitializationFailure;
        }
        for (uint32_t frame = traceInfo.frameStart; frame <= traceInfo.frameEnd; frame++)
        {
            mTraceLibrary->replayFrame(frame);
            const char *replayedSerializedState =
                reinterpret_cast<const char *>(glGetString(GL_SERIALIZED_CONTEXT_STRING_ANGLE));
            const char *capturedSerializedState = mTraceLibrary->getSerializedContextState(frame);
            if (replayedSerializedState == nullptr ||
                strlen(replayedSerializedState) <= kTooShortStateLength)
            {
                printf("Could not retrieve replay serialized state string.\n");
                return kSerializationFailure;
            }
            if (capturedSerializedState == nullptr ||
                strlen(capturedSerializedState) <= kTooShortStateLength)
            {
                printf("Could not retrieve captured serialized state string.\n");
                return kSerializationFailure;
            }
            // Swap always to allow RenderDoc/other tools to capture frames.
            swap();
            if (!CompareSerializedContexts(replayedSerializedState, capturedSerializedState))
            {
                printf("Serialized contexts differ, saving files.\n");
                std::ostringstream replayName;
                replayName << exeDir << angle::GetPathSeparator() << traceInfo.name
                           << "_ContextReplayed" << frame << ".json";
                std::ofstream debugReplay(replayName.str());
                if (!debugReplay)
                {
                    printf("Error opening debug replay stream.\n");
                }
                else
                {
                    debugReplay << (replayedSerializedState ? replayedSerializedState : "") << "\n";
                    printf("Wrote %s.\n", replayName.str().c_str());
                }
                std::ostringstream captureName;
                captureName << exeDir << angle::GetPathSeparator() << traceInfo.name
                            << "_ContextCaptured" << frame << ".json";
                std::ofstream debugCapture(captureName.str());
                if (!debugCapture)
                {
                    printf("Error opening debug capture stream.\n");
                }
                else
                {
                    debugCapture << (capturedSerializedState ? capturedSerializedState : "")
                                 << "\n";
                    printf("Wrote %s.\n", captureName.str().c_str());
                }
                cleanupTest();
                return kSerializationFailure;
            }
        }
        cleanupTest();
        return kExitSuccess;
    }
    int run(const char *trace)
    {
        std::string startingDirectory = angle::GetCWD().value();
        // Set CWD to executable directory.
        std::string exeDir = angle::GetExecutableDirectory();
        std::stringstream traceJsonPathStream;
        traceJsonPathStream << exeDir << angle::GetPathSeparator()
                            << ANGLE_CAPTURE_REPLAY_TEST_DATA_DIR << angle::GetPathSeparator()
                            << trace << ".json";
        std::string traceJsonPath = traceJsonPathStream.str();
        int result                 = kInitializationFailure;
        angle::TraceInfo traceInfo = {};
        if (!angle::LoadTraceInfoFromJSON(trace, traceJsonPath, &traceInfo))
        {
            std::cout << "Unable to load trace data: " << traceJsonPath << "\n";
        }
        else
        {
            result = runTest(exeDir, traceInfo);
        }
        std::cout << kResultTag << " " << trace << " " << result << "\n";
        angle::SetCWD(startingDirectory.c_str());
        return kExitSuccess;
    }
  private:
    OSWindow *mOSWindow   = nullptr;
    EGLWindow *mEGLWindow = nullptr;
    EGLPlatformParameters mPlatformParams;
    angle::PlatformMethods mPlatformMethods;
    // Handle to the entry point binding library.
    std::unique_ptr<angle::Library> mEntryPointsLib;
    std::unique_ptr<angle::TraceLibrary> mTraceLibrary;
};
int main(int argc, char **argv)
{
    if (argc != 2)
    {
        printf("Usage: capture_replay_tests {trace_label}\n");
        return -1;
    }
    angle::CrashCallback crashCallback = []() {};
    angle::InitCrashHandler(&crashCallback);
    CaptureReplayTests app;
    return app.run(argv[1]);
}