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.

Mercurial (c584e29f6ac2)

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 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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "WebGLContext.h"

#include <algorithm>
#include "GLSLANG/ShaderLang.h"
#include "CanvasUtils.h"
#include "GLContext.h"
#include "jsfriendapi.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPrefs_webgl.h"
#include "nsIObserverService.h"
#include "nsPrintfCString.h"
#include "WebGLActiveInfo.h"
#include "WebGLBuffer.h"
#include "WebGLContextUtils.h"
#include "WebGLFramebuffer.h"
#include "WebGLProgram.h"
#include "WebGLRenderbuffer.h"
#include "WebGLSampler.h"
#include "WebGLShader.h"
#include "WebGLTexture.h"
#include "WebGLUniformLocation.h"
#include "WebGLValidateStrings.h"
#include "WebGLVertexArray.h"
#include "WebGLVertexAttribData.h"

#if defined(MOZ_WIDGET_COCOA)
#  include "nsCocoaFeatures.h"
#endif

////////////////////
// Minimum value constants defined in GLES 2.0.25 $6.2 "State Tables":
const uint32_t kMinMaxVertexAttribs = 8;            // Page 164
const uint32_t kMinMaxVertexUniformVectors = 128;   // Page 164
const uint32_t kMinMaxFragmentUniformVectors = 16;  // Page 164
const uint32_t kMinMaxVaryingVectors = 8;           // Page 164

const uint32_t kMinMaxVertexTextureImageUnits = 0;    // Page 164
const uint32_t kMinMaxFragmentTextureImageUnits = 8;  // Page 164
const uint32_t kMinMaxCombinedTextureImageUnits = 8;  // Page 164

const uint32_t kMinMaxColorAttachments = 4;
const uint32_t kMinMaxDrawBuffers = 4;

// These few deviate from the spec: (The minimum values in the spec are
// ridiculously low)
const uint32_t kMinMaxTextureSize = 1024;        // ES2 spec says `64` (p162)
const uint32_t kMinMaxCubeMapTextureSize = 512;  // ES2 spec says `16` (p162)
const uint32_t kMinMaxRenderbufferSize = 1024;   // ES2 spec says `1` (p164)

// Minimum value constants defined in GLES 3.0.4 $6.2 "State Tables":
const uint32_t kMinMax3DTextureSize = 256;
const uint32_t kMinMaxArrayTextureLayers = 256;

////////////////////
// "Common" but usable values to avoid WebGL fingerprinting:
const uint32_t kCommonMaxTextureSize = 2048;
const uint32_t kCommonMaxCubeMapTextureSize = 2048;
const uint32_t kCommonMaxRenderbufferSize = 2048;

const uint32_t kCommonMaxVertexTextureImageUnits = 8;
const uint32_t kCommonMaxFragmentTextureImageUnits = 8;
const uint32_t kCommonMaxCombinedTextureImageUnits = 16;

const uint32_t kCommonMaxVertexAttribs = 16;
const uint32_t kCommonMaxVertexUniformVectors = 256;
const uint32_t kCommonMaxFragmentUniformVectors = 224;
const uint32_t kCommonMaxVaryingVectors = 8;

const uint32_t kCommonMaxViewportDims = 4096;

// The following ranges came from a 2013 Moto E and an old macbook.
const float kCommonAliasedPointSizeRangeMin = 1;
const float kCommonAliasedPointSizeRangeMax = 63;
const float kCommonAliasedLineWidthRangeMin = 1;
const float kCommonAliasedLineWidthRangeMax = 1;

template <class T>
static bool RestrictCap(T* const cap, const T restrictedVal) {
  if (*cap < restrictedVal) {
    return false;  // already too low!
  }

  *cap = restrictedVal;
  return true;
}

////////////////////

namespace mozilla {

bool WebGLContext::ValidateBlendEquationEnum(GLenum mode, const char* info) {
  switch (mode) {
    case LOCAL_GL_FUNC_ADD:
    case LOCAL_GL_FUNC_SUBTRACT:
    case LOCAL_GL_FUNC_REVERSE_SUBTRACT:
      return true;

    case LOCAL_GL_MIN:
    case LOCAL_GL_MAX:
      if (IsWebGL2() ||
          IsExtensionEnabled(WebGLExtensionID::EXT_blend_minmax)) {
        return true;
      }

      break;

    default:
      break;
  }

  ErrorInvalidEnumInfo(info, mode);
  return false;
}

bool WebGLContext::ValidateBlendFuncEnumsCompatibility(GLenum sfactor,
                                                       GLenum dfactor,
                                                       const char* info) {
  bool sfactorIsConstantColor = sfactor == LOCAL_GL_CONSTANT_COLOR ||
                                sfactor == LOCAL_GL_ONE_MINUS_CONSTANT_COLOR;
  bool sfactorIsConstantAlpha = sfactor == LOCAL_GL_CONSTANT_ALPHA ||
                                sfactor == LOCAL_GL_ONE_MINUS_CONSTANT_ALPHA;
  bool dfactorIsConstantColor = dfactor == LOCAL_GL_CONSTANT_COLOR ||
                                dfactor == LOCAL_GL_ONE_MINUS_CONSTANT_COLOR;
  bool dfactorIsConstantAlpha = dfactor == LOCAL_GL_CONSTANT_ALPHA ||
                                dfactor == LOCAL_GL_ONE_MINUS_CONSTANT_ALPHA;
  if ((sfactorIsConstantColor && dfactorIsConstantAlpha) ||
      (dfactorIsConstantColor && sfactorIsConstantAlpha)) {
    ErrorInvalidOperation(
        "%s are mutually incompatible, see section 6.8 in"
        " the WebGL 1.0 spec",
        info);
    return false;
  }

  return true;
}

bool WebGLContext::ValidateStencilOpEnum(GLenum action, const char* info) {
  switch (action) {
    case LOCAL_GL_KEEP:
    case LOCAL_GL_ZERO:
    case LOCAL_GL_REPLACE:
    case LOCAL_GL_INCR:
    case LOCAL_GL_INCR_WRAP:
    case LOCAL_GL_DECR:
    case LOCAL_GL_DECR_WRAP:
    case LOCAL_GL_INVERT:
      return true;

    default:
      ErrorInvalidEnumInfo(info, action);
      return false;
  }
}

bool WebGLContext::ValidateFaceEnum(const GLenum face) {
  switch (face) {
    case LOCAL_GL_FRONT:
    case LOCAL_GL_BACK:
    case LOCAL_GL_FRONT_AND_BACK:
      return true;

    default:
      ErrorInvalidEnumInfo("face", face);
      return false;
  }
}

bool WebGLContext::ValidateUniformLocation(
    const WebGLUniformLocation* const loc) {
  /* GLES 2.0.25, p38:
   *   If the value of location is -1, the Uniform* commands will silently
   *   ignore the data passed in, and the current uniform values will not be
   *   changed.
   */
  if (!loc) return false;

  if (!ValidateObjectAllowDeleted("loc", *loc)) return false;

  if (!mCurrentProgram) {
    ErrorInvalidOperation("No program is currently bound.");
    return false;
  }

  return loc->ValidateForProgram(mCurrentProgram);
}

bool WebGLContext::ValidateAttribArraySetter(uint32_t setterElemSize,
                                             uint32_t arrayLength) {
  if (IsContextLost()) return false;

  if (arrayLength < setterElemSize) {
    ErrorInvalidValue("Array must have >= %d elements.", setterElemSize);
    return false;
  }

  return true;
}

bool WebGLContext::ValidateUniformSetter(
    const WebGLUniformLocation* const loc, const uint8_t setterElemSize,
    const webgl::AttribBaseType setterType) {
  if (IsContextLost()) return false;

  if (!ValidateUniformLocation(loc)) return false;

  if (!loc->ValidateSizeAndType(setterElemSize, setterType)) return false;

  return true;
}

bool WebGLContext::ValidateUniformArraySetter(
    const WebGLUniformLocation* const loc, const uint8_t setterElemSize,
    const webgl::AttribBaseType setterType, const uint32_t setterArraySize,
    uint32_t* const out_numElementsToUpload) {
  if (IsContextLost()) return false;

  if (!ValidateUniformLocation(loc)) return false;

  if (!loc->ValidateSizeAndType(setterElemSize, setterType)) return false;

  if (!loc->ValidateArrayLength(setterElemSize, setterArraySize)) return false;

  const auto& elemCount = loc->mInfo->mActiveInfo->mElemCount;
  MOZ_ASSERT(elemCount > loc->mArrayIndex);
  const uint32_t uniformElemCount = elemCount - loc->mArrayIndex;

  *out_numElementsToUpload =
      std::min(uniformElemCount, setterArraySize / setterElemSize);
  return true;
}

bool WebGLContext::ValidateUniformMatrixArraySetter(
    const WebGLUniformLocation* const loc, const uint8_t setterCols,
    const uint8_t setterRows, const webgl::AttribBaseType setterType,
    const uint32_t setterArraySize, const bool setterTranspose,
    uint32_t* const out_numElementsToUpload) {
  const uint8_t setterElemSize = setterCols * setterRows;

  if (IsContextLost()) return false;

  if (!ValidateUniformLocation(loc)) return false;

  if (!loc->ValidateSizeAndType(setterElemSize, setterType)) return false;

  if (!loc->ValidateArrayLength(setterElemSize, setterArraySize)) return false;

  if (setterTranspose && !IsWebGL2()) {
    ErrorInvalidValue("`transpose` must be false.");
    return false;
  }

  const auto& elemCount = loc->mInfo->mActiveInfo->mElemCount;
  MOZ_ASSERT(elemCount > loc->mArrayIndex);
  const uint32_t uniformElemCount = elemCount - loc->mArrayIndex;

  *out_numElementsToUpload =
      std::min(uniformElemCount, setterArraySize / setterElemSize);
  return true;
}

bool WebGLContext::InitAndValidateGL(FailureReason* const out_failReason) {
  MOZ_RELEASE_ASSERT(gl, "GFX: GL not initialized");

  // Unconditionally create a new format usage authority. This is
  // important when restoring contexts and extensions need to add
  // formats back into the authority.
  mFormatUsage = CreateFormatUsage(gl);
  if (!mFormatUsage) {
    *out_failReason = {"FEATURE_FAILURE_WEBGL_FORMAT",
                       "Failed to create mFormatUsage."};
    return false;
  }

  GLenum error = gl->fGetError();
  if (error != LOCAL_GL_NO_ERROR) {
    const nsPrintfCString reason(
        "GL error 0x%x occurred during OpenGL context"
        " initialization, before WebGL initialization!",
        error);
    *out_failReason = {"FEATURE_FAILURE_WEBGL_GLERR_1", reason};
    return false;
  }

  mDisableExtensions = StaticPrefs::webgl_disable_extensions();
  mLoseContextOnMemoryPressure =
      StaticPrefs::webgl_lose_context_on_memory_pressure();
  mCanLoseContextInForeground =
      StaticPrefs::webgl_can_lose_context_in_foreground();

  // These are the default values, see 6.2 State tables in the
  // OpenGL ES 2.0.25 spec.
  mColorWriteMask = 0x0f;
  mDriverColorMask = mColorWriteMask;
  mColorClearValue[0] = 0.f;
  mColorClearValue[1] = 0.f;
  mColorClearValue[2] = 0.f;
  mColorClearValue[3] = 0.f;
  mDepthWriteMask = true;
  mDepthClearValue = 1.f;
  mStencilClearValue = 0;
  mStencilRefFront = 0;
  mStencilRefBack = 0;

  mLineWidth = 1.0;

  /*
  // Technically, we should be setting mStencil[...] values to
  // `allOnes`, but either ANGLE breaks or the SGX540s on Try break.
  GLuint stencilBits = 0;
  gl->GetUIntegerv(LOCAL_GL_STENCIL_BITS, &stencilBits);
  GLuint allOnes = ~(UINT32_MAX << stencilBits);
  mStencilValueMaskFront = allOnes;
  mStencilValueMaskBack  = allOnes;
  mStencilWriteMaskFront = allOnes;
  mStencilWriteMaskBack  = allOnes;
  */

  gl->GetUIntegerv(LOCAL_GL_STENCIL_VALUE_MASK, &mStencilValueMaskFront);
  gl->GetUIntegerv(LOCAL_GL_STENCIL_BACK_VALUE_MASK, &mStencilValueMaskBack);
  gl->GetUIntegerv(LOCAL_GL_STENCIL_WRITEMASK, &mStencilWriteMaskFront);
  gl->GetUIntegerv(LOCAL_GL_STENCIL_BACK_WRITEMASK, &mStencilWriteMaskBack);

  AssertUintParamCorrect(gl, LOCAL_GL_STENCIL_VALUE_MASK,
                         mStencilValueMaskFront);
  AssertUintParamCorrect(gl, LOCAL_GL_STENCIL_BACK_VALUE_MASK,
                         mStencilValueMaskBack);
  AssertUintParamCorrect(gl, LOCAL_GL_STENCIL_WRITEMASK,
                         mStencilWriteMaskFront);
  AssertUintParamCorrect(gl, LOCAL_GL_STENCIL_BACK_WRITEMASK,
                         mStencilWriteMaskBack);

  mDitherEnabled = true;
  mRasterizerDiscardEnabled = false;
  mScissorTestEnabled = false;

  mDepthTestEnabled = 0;
  mDriverDepthTest = false;
  mStencilTestEnabled = 0;
  mDriverStencilTest = false;

  mGenerateMipmapHint = LOCAL_GL_DONT_CARE;

  // Bindings, etc.
  mActiveTexture = 0;
  mDefaultFB_DrawBuffer0 = LOCAL_GL_BACK;
  mDefaultFB_ReadBuffer = LOCAL_GL_BACK;

  mWebGLError = LOCAL_GL_NO_ERROR;

  mBound2DTextures.Clear();
  mBoundCubeMapTextures.Clear();
  mBound3DTextures.Clear();
  mBound2DArrayTextures.Clear();
  mBoundSamplers.Clear();

  mBoundArrayBuffer = nullptr;
  mCurrentProgram = nullptr;

  mBoundDrawFramebuffer = nullptr;
  mBoundReadFramebuffer = nullptr;
  mBoundRenderbuffer = nullptr;

  gl->GetUIntegerv(LOCAL_GL_MAX_VERTEX_ATTRIBS, &mGLMaxVertexAttribs);

  if (mGLMaxVertexAttribs < 8) {
    const nsPrintfCString reason("GL_MAX_VERTEX_ATTRIBS: %d is < 8!",
                                 mGLMaxVertexAttribs);
    *out_failReason = {"FEATURE_FAILURE_WEBGL_V_ATRB", reason};
    return false;
  }

  // Note: GL_MAX_TEXTURE_UNITS is fixed at 4 for most desktop hardware,
  // even though the hardware supports much more.  The
  // GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS value is the accurate value.
  mGLMaxCombinedTextureImageUnits =
      gl->GetIntAs<GLuint>(LOCAL_GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  mGLMaxTextureUnits = mGLMaxCombinedTextureImageUnits;

  if (mGLMaxCombinedTextureImageUnits < 8) {
    const nsPrintfCString reason(
        "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: %u is < 8!", mGLMaxTextureUnits);
    *out_failReason = {"FEATURE_FAILURE_WEBGL_T_UNIT", reason};
    return false;
  }

  mBound2DTextures.SetLength(mGLMaxTextureUnits);
  mBoundCubeMapTextures.SetLength(mGLMaxTextureUnits);
  mBound3DTextures.SetLength(mGLMaxTextureUnits);
  mBound2DArrayTextures.SetLength(mGLMaxTextureUnits);
  mBoundSamplers.SetLength(mGLMaxTextureUnits);

  gl->fGetIntegerv(LOCAL_GL_MAX_VIEWPORT_DIMS, (GLint*)mGLMaxViewportDims);

  ////////////////

  gl->fGetIntegerv(LOCAL_GL_MAX_TEXTURE_SIZE, (GLint*)&mGLMaxTextureSize);
  gl->fGetIntegerv(LOCAL_GL_MAX_CUBE_MAP_TEXTURE_SIZE,
                   (GLint*)&mGLMaxCubeMapTextureSize);
  gl->fGetIntegerv(LOCAL_GL_MAX_RENDERBUFFER_SIZE,
                   (GLint*)&mGLMaxRenderbufferSize);

  if (!gl->GetPotentialInteger(LOCAL_GL_MAX_3D_TEXTURE_SIZE,
                               (GLint*)&mGLMax3DTextureSize))
    mGLMax3DTextureSize = 0;
  if (!gl->GetPotentialInteger(LOCAL_GL_MAX_ARRAY_TEXTURE_LAYERS,
                               (GLint*)&mGLMaxArrayTextureLayers))
    mGLMaxArrayTextureLayers = 0;

  (void)gl->GetPotentialInteger(LOCAL_GL_MAX_VIEWS_OVR,
                                (GLint*)&mGLMaxMultiviewViews);

  gl->GetUIntegerv(LOCAL_GL_MAX_TEXTURE_IMAGE_UNITS,
                   &mGLMaxFragmentTextureImageUnits);
  gl->GetUIntegerv(LOCAL_GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
                   &mGLMaxVertexTextureImageUnits);

  ////////////////

  mGLMaxColorAttachments = 1;
  mGLMaxDrawBuffers = 1;

  if (IsWebGL2()) {
    UpdateMaxDrawBuffers();
  }

  ////////////////

  if (gl->IsGLES()) {
    mGLMaxFragmentUniformVectors =
        gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_FRAGMENT_UNIFORM_VECTORS);
    mGLMaxVertexUniformVectors =
        gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_VERTEX_UNIFORM_VECTORS);
    if (gl->Version() >= 300) {
      mGLMaxVertexOutputVectors =
          gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_VERTEX_OUTPUT_COMPONENTS) / 4;
      mGLMaxFragmentInputVectors =
          gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_FRAGMENT_INPUT_COMPONENTS) / 4;
    } else {
      mGLMaxFragmentInputVectors =
          gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_VARYING_VECTORS);
      mGLMaxVertexOutputVectors = mGLMaxFragmentInputVectors;
    }
  } else {
    mGLMaxFragmentUniformVectors =
        gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_FRAGMENT_UNIFORM_COMPONENTS) / 4;
    mGLMaxVertexUniformVectors =
        gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_VERTEX_UNIFORM_COMPONENTS) / 4;

    if (gl->Version() >= 320) {
      mGLMaxVertexOutputVectors =
          gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_VERTEX_OUTPUT_COMPONENTS) / 4;
      mGLMaxFragmentInputVectors =
          gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_FRAGMENT_INPUT_COMPONENTS) / 4;
    } else {
      // Same enum val as GL2's GL_MAX_VARYING_FLOATS.
      mGLMaxFragmentInputVectors =
          gl->GetIntAs<uint32_t>(LOCAL_GL_MAX_VARYING_COMPONENTS) / 4;
      mGLMaxVertexOutputVectors = mGLMaxFragmentInputVectors;
    }
  }

  ////////////////

  if (gl->IsCoreProfile()) {
    mGLAliasedLineWidthRange[0] = 1.0f;
    mGLAliasedLineWidthRange[1] = 1.0f;
  } else {
    gl->fGetFloatv(LOCAL_GL_ALIASED_LINE_WIDTH_RANGE, mGLAliasedLineWidthRange);
  }

  const GLenum driverPName = gl->IsCoreProfile()
                                 ? LOCAL_GL_POINT_SIZE_RANGE
                                 : LOCAL_GL_ALIASED_POINT_SIZE_RANGE;
  gl->fGetFloatv(driverPName, mGLAliasedPointSizeRange);

  ////////////////

  if (StaticPrefs::webgl_min_capability_mode()) {
    bool ok = true;

    ok &= RestrictCap(&mGLMaxVertexTextureImageUnits,
                      kMinMaxVertexTextureImageUnits);
    ok &= RestrictCap(&mGLMaxFragmentTextureImageUnits,
                      kMinMaxFragmentTextureImageUnits);
    ok &= RestrictCap(&mGLMaxCombinedTextureImageUnits,
                      kMinMaxCombinedTextureImageUnits);

    ok &= RestrictCap(&mGLMaxVertexAttribs, kMinMaxVertexAttribs);
    ok &= RestrictCap(&mGLMaxVertexUniformVectors, kMinMaxVertexUniformVectors);
    ok &= RestrictCap(&mGLMaxFragmentUniformVectors,
                      kMinMaxFragmentUniformVectors);
    ok &= RestrictCap(&mGLMaxVertexOutputVectors, kMinMaxVaryingVectors);
    ok &= RestrictCap(&mGLMaxFragmentInputVectors, kMinMaxVaryingVectors);

    ok &= RestrictCap(&mGLMaxColorAttachments, kMinMaxColorAttachments);
    ok &= RestrictCap(&mGLMaxDrawBuffers, kMinMaxDrawBuffers);

    ok &= RestrictCap(&mGLMaxTextureSize, kMinMaxTextureSize);
    ok &= RestrictCap(&mGLMaxCubeMapTextureSize, kMinMaxCubeMapTextureSize);
    ok &= RestrictCap(&mGLMax3DTextureSize, kMinMax3DTextureSize);

    ok &= RestrictCap(&mGLMaxArrayTextureLayers, kMinMaxArrayTextureLayers);
    ok &= RestrictCap(&mGLMaxRenderbufferSize, kMinMaxRenderbufferSize);

    if (!ok) {
      GenerateWarning("Unable to restrict WebGL limits to minimums.");
      return false;
    }

    mDisableFragHighP = true;
  } else if (ShouldResistFingerprinting()) {
    bool ok = true;

    ok &= RestrictCap(&mGLMaxTextureSize, kCommonMaxTextureSize);
    ok &= RestrictCap(&mGLMaxCubeMapTextureSize, kCommonMaxCubeMapTextureSize);
    ok &= RestrictCap(&mGLMaxRenderbufferSize, kCommonMaxRenderbufferSize);

    ok &= RestrictCap(&mGLMaxVertexTextureImageUnits,
                      kCommonMaxVertexTextureImageUnits);
    ok &= RestrictCap(&mGLMaxFragmentTextureImageUnits,
                      kCommonMaxFragmentTextureImageUnits);
    ok &= RestrictCap(&mGLMaxCombinedTextureImageUnits,
                      kCommonMaxCombinedTextureImageUnits);

    ok &= RestrictCap(&mGLMaxVertexAttribs, kCommonMaxVertexAttribs);
    ok &= RestrictCap(&mGLMaxVertexUniformVectors,
                      kCommonMaxVertexUniformVectors);
    ok &= RestrictCap(&mGLMaxFragmentUniformVectors,
                      kCommonMaxFragmentUniformVectors);
    ok &= RestrictCap(&mGLMaxVertexOutputVectors, kCommonMaxVaryingVectors);
    ok &= RestrictCap(&mGLMaxFragmentInputVectors, kCommonMaxVaryingVectors);

    ok &= RestrictCap(&mGLAliasedLineWidthRange[0],
                      kCommonAliasedLineWidthRangeMin);
    ok &= RestrictCap(&mGLAliasedLineWidthRange[1],
                      kCommonAliasedLineWidthRangeMax);
    ok &= RestrictCap(&mGLAliasedPointSizeRange[0],
                      kCommonAliasedPointSizeRangeMin);
    ok &= RestrictCap(&mGLAliasedPointSizeRange[1],
                      kCommonAliasedPointSizeRangeMax);

    ok &= RestrictCap(&mGLMaxViewportDims[0], kCommonMaxViewportDims);
    ok &= RestrictCap(&mGLMaxViewportDims[1], kCommonMaxViewportDims);

    if (!ok) {
      GenerateWarning(
          "Unable to restrict WebGL limits in order to resist fingerprinting");
      return false;
    }
  }

  ////////////////

  if (gl->IsCompatibilityProfile()) {
    gl->fEnable(LOCAL_GL_POINT_SPRITE);
  }

  if (!gl->IsGLES()) {
    gl->fEnable(LOCAL_GL_PROGRAM_POINT_SIZE);
  }

#ifdef XP_MACOSX
  if (gl->WorkAroundDriverBugs() && gl->Vendor() == gl::GLVendor::ATI &&
      !nsCocoaFeatures::IsAtLeastVersion(10, 9)) {
    // The Mac ATI driver, in all known OSX version up to and including
    // 10.8, renders points sprites upside-down. (Apple bug 11778921)
    gl->fPointParameterf(LOCAL_GL_POINT_SPRITE_COORD_ORIGIN,
                         LOCAL_GL_LOWER_LEFT);
  }
#endif

  if (gl->IsSupported(gl::GLFeature::seamless_cube_map_opt_in)) {
    gl->fEnable(LOCAL_GL_TEXTURE_CUBE_MAP_SEAMLESS);
  }

  // initialize shader translator
  if (!sh::Initialize()) {
    *out_failReason = {"FEATURE_FAILURE_WEBGL_GLSL",
                       "GLSL translator initialization failed!"};
    return false;
  }

  // Mesa can only be detected with the GL_VERSION string, of the form
  // "2.1 Mesa 7.11.0"
  const char* versionStr = (const char*)(gl->fGetString(LOCAL_GL_VERSION));
  mIsMesa = strstr(versionStr, "Mesa");

  // Notice that the point of calling fGetError here is not only to check for
  // errors, but also to reset the error flags so that a subsequent WebGL
  // getError call will give the correct result.
  error = gl->fGetError();
  if (error != LOCAL_GL_NO_ERROR) {
    const nsPrintfCString reason(
        "GL error 0x%x occurred during WebGL context"
        " initialization!",
        error);
    *out_failReason = {"FEATURE_FAILURE_WEBGL_GLERR_2", reason};
    return false;
  }

  if (IsWebGL2() && !InitWebGL2(out_failReason)) {
    // Todo: Bug 898404: Only allow WebGL2 on GL>=3.0 on desktop GL.
    return false;
  }

  if (!gl->IsSupported(GLFeature::vertex_array_object)) {
    *out_failReason = {"FEATURE_FAILURE_WEBGL_VAOS",
                       "Requires vertex_array_object."};
    return false;
  }

  // OpenGL core profiles remove the default VAO object from version
  // 4.0.0. We create a default VAO for all core profiles,
  // regardless of version.
  //
  // GL Spec 4.0.0:
  // (https://www.opengl.org/registry/doc/glspec40.core.20100311.pdf)
  // in Section E.2.2 "Removed Features", pg 397: "[...] The default
  // vertex array object (the name zero) is also deprecated. [...]"
  mDefaultVertexArray = WebGLVertexArray::Create(this);
  mDefaultVertexArray->BindVertexArray();
  mDefaultVertexArray->mAttribs.resize(mGLMaxVertexAttribs);

  mPixelStore_FlipY = false;
  mPixelStore_PremultiplyAlpha = false;
  mPixelStore_ColorspaceConversion = BROWSER_DEFAULT_WEBGL;
  mPixelStore_RequireFastPath = false;

  // GLES 3.0.4, p259:
  mPixelStore_UnpackImageHeight = 0;
  mPixelStore_UnpackSkipImages = 0;
  mPixelStore_UnpackRowLength = 0;
  mPixelStore_UnpackSkipRows = 0;
  mPixelStore_UnpackSkipPixels = 0;
  mPixelStore_UnpackAlignment = 4;
  mPixelStore_PackRowLength = 0;
  mPixelStore_PackSkipRows = 0;
  mPixelStore_PackSkipPixels = 0;
  mPixelStore_PackAlignment = 4;

  mPrimRestartTypeBytes = 0;

  mGenericVertexAttribTypes.assign(mGLMaxVertexAttribs,
                                   webgl::AttribBaseType::Float);
  mGenericVertexAttribTypeInvalidator.InvalidateCaches();

  static const float kDefaultGenericVertexAttribData[4] = {0, 0, 0, 1};
  memcpy(mGenericVertexAttrib0Data, kDefaultGenericVertexAttribData,
         sizeof(mGenericVertexAttrib0Data));

  mFakeVertexAttrib0BufferObject = 0;

  mNeedsIndexValidation =
      !gl->IsSupported(gl::GLFeature::robust_buffer_access_behavior);
  switch (StaticPrefs::webgl_force_index_validation()) {
    case -1:
      mNeedsIndexValidation = false;
      break;
    case 1:
      mNeedsIndexValidation = true;
      break;
    default:
      MOZ_ASSERT(StaticPrefs::webgl_force_index_validation() == 0);
      break;
  }

  return true;
}

bool WebGLContext::ValidateFramebufferTarget(GLenum target) const {
  bool isValid = true;
  switch (target) {
    case LOCAL_GL_FRAMEBUFFER:
      break;

    case LOCAL_GL_DRAW_FRAMEBUFFER:
    case LOCAL_GL_READ_FRAMEBUFFER:
      isValid = IsWebGL2();
      break;

    default:
      isValid = false;
      break;
  }

  if (MOZ_LIKELY(isValid)) {
    return true;
  }

  ErrorInvalidEnumArg("target", target);
  return false;
}

}  // namespace mozilla