summaryrefslogtreecommitdiffstats
path: root/dom/webgpu/tests/cts/checkout/src/webgpu/shader/execution/robust_access.spec.ts
blob: 69f92beaabb9ab456e105cf585fa1a8a169b86e3 (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
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
export const description = `
Tests to check datatype clamping in shaders is correctly implemented for all indexable types
(vectors, matrices, sized/unsized arrays) visible to shaders in various ways.

TODO: add tests to check that textureLoad operations stay in-bounds.
`;

import { makeTestGroup } from '../../../common/framework/test_group.js';
import { assert } from '../../../common/util/util.js';
import { GPUTest } from '../../gpu_test.js';
import { align } from '../../util/math.js';
import { generateTypes, supportedScalarTypes, supportsAtomics } from '../types.js';

export const g = makeTestGroup(GPUTest);

const kMaxU32 = 0xffff_ffff;
const kMaxI32 = 0x7fff_ffff;
const kMinI32 = -0x8000_0000;

/**
 * Wraps the provided source into a harness that checks calling `runTest()` returns 0.
 *
 * Non-test bindings are in bind group 1, including:
 * - `constants.zero`: a dynamically-uniform `0u` value.
 */
function runShaderTest(
  t: GPUTest,
  stage: GPUShaderStageFlags,
  testSource: string,
  layout: GPUPipelineLayout,
  testBindings: GPUBindGroupEntry[],
  dynamicOffsets?: number[]
): void {
  assert(stage === GPUShaderStage.COMPUTE, 'Only know how to deal with compute for now');

  // Contains just zero (for now).
  const constantsBuffer = t.device.createBuffer({ size: 4, usage: GPUBufferUsage.UNIFORM });

  const resultBuffer = t.device.createBuffer({
    size: 4,
    usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.STORAGE,
  });

  const source = `
struct Constants {
  zero: u32
};
@group(1) @binding(0) var<uniform> constants: Constants;

struct Result {
  value: u32
};
@group(1) @binding(1) var<storage, read_write> result: Result;

${testSource}

@compute @workgroup_size(1)
fn main() {
  _ = constants.zero; // Ensure constants buffer is statically-accessed
  result.value = runTest();
}`;

  t.debug(source);
  const module = t.device.createShaderModule({ code: source });
  const pipeline = t.device.createComputePipeline({
    layout,
    compute: { module, entryPoint: 'main' },
  });

  const group = t.device.createBindGroup({
    layout: pipeline.getBindGroupLayout(1),
    entries: [
      { binding: 0, resource: { buffer: constantsBuffer } },
      { binding: 1, resource: { buffer: resultBuffer } },
    ],
  });

  const testGroup = t.device.createBindGroup({
    layout: pipeline.getBindGroupLayout(0),
    entries: testBindings,
  });

  const encoder = t.device.createCommandEncoder();
  const pass = encoder.beginComputePass();
  pass.setPipeline(pipeline);
  pass.setBindGroup(0, testGroup, dynamicOffsets);
  pass.setBindGroup(1, group);
  pass.dispatchWorkgroups(1);
  pass.end();

  t.queue.submit([encoder.finish()]);

  t.expectGPUBufferValuesEqual(resultBuffer, new Uint32Array([0]));
}

/** Fill an ArrayBuffer with sentinel values, except clear a region to zero. */
function testFillArrayBuffer(
  array: ArrayBuffer,
  type: 'u32' | 'i32' | 'f32',
  { zeroByteStart, zeroByteCount }: { zeroByteStart: number; zeroByteCount: number }
) {
  const constructor = { u32: Uint32Array, i32: Int32Array, f32: Float32Array }[type];
  assert(zeroByteCount % constructor.BYTES_PER_ELEMENT === 0);
  new constructor(array).fill(42);
  new constructor(array, zeroByteStart, zeroByteCount / constructor.BYTES_PER_ELEMENT).fill(0);
}

/**
 * Generate a bunch of indexable types (vec, mat, sized/unsized array) for testing.
 */

g.test('linear_memory')
  .desc(
    `For each indexable data type (vec, mat, sized/unsized array, of various scalar types), attempts
    to access (read, write, atomic load/store) a region of memory (buffer or internal) at various
    (signed/unsigned) indices. Checks that the accesses conform to robust access (OOB reads only
    return bound memory, OOB writes don't write OOB).

    TODO: Test in/out storage classes.
    TODO: Test vertex and fragment stages.
    TODO: Test using a dynamic offset instead of a static offset into uniform/storage bindings.
    TODO: Test types like vec2<atomic<i32>>, if that's allowed.
    TODO: Test exprIndexAddon as constexpr.
    TODO: Test exprIndexAddon as pipeline-overridable constant expression.
  `
  )
  .params(u =>
    u
      .combineWithParams([
        { storageClass: 'storage', storageMode: 'read', access: 'read', dynamicOffset: false },
        {
          storageClass: 'storage',
          storageMode: 'read_write',
          access: 'read',
          dynamicOffset: false,
        },
        {
          storageClass: 'storage',
          storageMode: 'read_write',
          access: 'write',
          dynamicOffset: false,
        },
        { storageClass: 'storage', storageMode: 'read', access: 'read', dynamicOffset: true },
        { storageClass: 'storage', storageMode: 'read_write', access: 'read', dynamicOffset: true },
        {
          storageClass: 'storage',
          storageMode: 'read_write',
          access: 'write',
          dynamicOffset: true,
        },
        { storageClass: 'uniform', access: 'read', dynamicOffset: false },
        { storageClass: 'uniform', access: 'read', dynamicOffset: true },
        { storageClass: 'private', access: 'read' },
        { storageClass: 'private', access: 'write' },
        { storageClass: 'function', access: 'read' },
        { storageClass: 'function', access: 'write' },
        { storageClass: 'workgroup', access: 'read' },
        { storageClass: 'workgroup', access: 'write' },
      ] as const)
      .combineWithParams([
        { containerType: 'array' },
        { containerType: 'matrix' },
        { containerType: 'vector' },
      ] as const)
      .combineWithParams([
        { shadowingMode: 'none' },
        { shadowingMode: 'module-scope' },
        { shadowingMode: 'function-scope' },
      ])
      .expand('isAtomic', p => (supportsAtomics(p) ? [false, true] : [false]))
      .beginSubcases()
      .expand('baseType', supportedScalarTypes)
      .expandWithParams(generateTypes)
  )
  .fn(async t => {
    const {
      storageClass,
      storageMode,
      access,
      dynamicOffset,
      isAtomic,
      containerType,
      baseType,
      type,
      shadowingMode,
      _kTypeInfo,
    } = t.params;

    assert(_kTypeInfo !== undefined, 'not an indexable type');
    assert('arrayLength' in _kTypeInfo);

    let usesCanary = false;
    let globalSource = '';
    let testFunctionSource = '';
    const testBufferSize = 512;
    const bufferBindingOffset = 256;
    /** Undefined if no buffer binding is needed */
    let bufferBindingSize: number | undefined = undefined;

    // Declare the data that will be accessed to check robust access, as a buffer or a struct
    // in the global scope or inside the test function itself.
    const structDecl = `
struct S {
  startCanary: array<u32, 10>,
  data: ${type},
  endCanary: array<u32, 10>,
};`;

    const testGroupBGLEntires: GPUBindGroupLayoutEntry[] = [];
    switch (storageClass) {
      case 'uniform':
      case 'storage':
        {
          assert(_kTypeInfo.layout !== undefined);
          const layout = _kTypeInfo.layout;
          bufferBindingSize = align(layout.size, layout.alignment);
          const qualifiers = storageClass === 'storage' ? `storage, ${storageMode}` : storageClass;
          globalSource += `
struct TestData {
  data: ${type},
};
@group(0) @binding(0) var<${qualifiers}> s: TestData;`;

          testGroupBGLEntires.push({
            binding: 0,
            visibility: GPUShaderStage.COMPUTE,
            buffer: {
              type:
                storageClass === 'uniform'
                  ? 'uniform'
                  : storageMode === 'read'
                  ? 'read-only-storage'
                  : 'storage',
              hasDynamicOffset: dynamicOffset,
            },
          });
        }
        break;

      case 'private':
      case 'workgroup':
        usesCanary = true;
        globalSource += structDecl;
        globalSource += `var<${storageClass}> s: S;`;
        break;

      case 'function':
        usesCanary = true;
        globalSource += structDecl;
        testFunctionSource += 'var s: S;';
        break;
    }

    // Build the test function that will do the tests.

    // If we use a local canary declared in the shader, initialize it.
    if (usesCanary) {
      testFunctionSource += `
  for (var i = 0u; i < 10u; i = i + 1u) {
    s.startCanary[i] = 0xFFFFFFFFu;
    s.endCanary[i] = 0xFFFFFFFFu;
  }`;
    }

    /** Returns a different number each time, kind of like a `__LINE__` to ID the failing check. */
    const nextErrorReturnValue = (() => {
      let errorReturnValue = 0x1000;
      return () => {
        ++errorReturnValue;
        return `0x${errorReturnValue.toString(16)}u`;
      };
    })();

    // This is here, instead of in subcases, so only a single shader is needed to test many modes.
    for (const indexSigned of [false, true]) {
      const indicesToTest = indexSigned
        ? [
            // Exactly in bounds (should be OK)
            '0',
            `${_kTypeInfo.arrayLength} - 1`,
            // Exactly out of bounds
            '-1',
            `${_kTypeInfo.arrayLength}`,
            // Far out of bounds
            '-1000000',
            '1000000',
            `${kMinI32}`,
            `${kMaxI32}`,
          ]
        : [
            // Exactly in bounds (should be OK)
            '0u',
            `${_kTypeInfo.arrayLength}u - 1u`,
            // Exactly out of bounds
            `${_kTypeInfo.arrayLength}u`,
            // Far out of bounds
            '1000000u',
            `${kMaxU32}u`,
            `${kMaxI32}u`,
          ];

      const indexTypeLiteral = indexSigned ? '0' : '0u';
      const indexTypeCast = indexSigned ? 'i32' : 'u32';
      for (const exprIndexAddon of [
        '', // No addon
        ` + ${indexTypeLiteral}`, // Add a literal 0
        ` + ${indexTypeCast}(constants.zero)`, // Add a uniform 0
      ]) {
        // Produce the accesses to the variable.
        for (const indexToTest of indicesToTest) {
          testFunctionSource += `
  {
    let index = (${indexToTest})${exprIndexAddon};`;
          const exprZeroElement = `${_kTypeInfo.elementBaseType}()`;
          const exprElement = `s.data[index]`;

          switch (access) {
            case 'read':
              {
                let exprLoadElement = isAtomic ? `atomicLoad(&${exprElement})` : exprElement;
                if (storageClass === 'uniform' && containerType === 'array') {
                  // Scalar types will be wrapped in a vec4 to satisfy array element size
                  // requirements for the uniform address space, so we need an additional index
                  // accessor expression.
                  exprLoadElement += '[0]';
                }
                let condition = `${exprLoadElement} != ${exprZeroElement}`;
                if (containerType === 'matrix') condition = `any(${condition})`;
                testFunctionSource += `
    if (${condition}) { return ${nextErrorReturnValue()}; }`;
              }
              break;

            case 'write':
              if (isAtomic) {
                testFunctionSource += `
    atomicStore(&s.data[index], ${exprZeroElement});`;
              } else {
                testFunctionSource += `
    s.data[index] = ${exprZeroElement};`;
              }
              break;
          }
          testFunctionSource += `
  }`;
        }
      }
    }

    // Check that the canaries haven't been modified
    if (usesCanary) {
      testFunctionSource += `
  for (var i = 0u; i < 10u; i = i + 1u) {
    if (s.startCanary[i] != 0xFFFFFFFFu) {
      return ${nextErrorReturnValue()};
    }
    if (s.endCanary[i] != 0xFFFFFFFFu) {
      return ${nextErrorReturnValue()};
    }
  }`;
    }

    // Shadowing case declarations
    let moduleScopeShadowDecls = '';
    let functionScopeShadowDecls = '';

    switch (shadowingMode) {
      case 'module-scope':
        // Shadow the builtins likely used by robustness as module-scope variables
        moduleScopeShadowDecls = `
var<private> min = 0;
var<private> max = 0;
var<private> arrayLength = 0;
`;
        // Make sure that these are referenced by the function.
        // This ensures that compilers don't strip away unused variables.
        functionScopeShadowDecls = `
  _ = min;
  _ = max;
  _ = arrayLength;
`;
        break;
      case 'function-scope':
        // Shadow the builtins likely used by robustness as function-scope variables
        functionScopeShadowDecls = `
  let min = 0;
  let max = 0;
  let arrayLength = 0;
`;
        break;
    }

    // Run the test

    // First aggregate the test source
    const testSource = `
${globalSource}
${moduleScopeShadowDecls}

fn runTest() -> u32 {
  ${functionScopeShadowDecls}
  ${testFunctionSource}
  return 0u;
}`;

    const layout = t.device.createPipelineLayout({
      bindGroupLayouts: [
        t.device.createBindGroupLayout({
          entries: testGroupBGLEntires,
        }),
        t.device.createBindGroupLayout({
          entries: [
            {
              binding: 0,
              visibility: GPUShaderStage.COMPUTE,
              buffer: {
                type: 'uniform',
              },
            },
            {
              binding: 1,
              visibility: GPUShaderStage.COMPUTE,
              buffer: {
                type: 'storage',
              },
            },
          ],
        }),
      ],
    });

    // Run it.
    if (bufferBindingSize !== undefined && baseType !== 'bool') {
      const expectedData = new ArrayBuffer(testBufferSize);
      const bufferBindingEnd = bufferBindingOffset + bufferBindingSize;
      testFillArrayBuffer(expectedData, baseType, {
        zeroByteStart: bufferBindingOffset,
        zeroByteCount: bufferBindingSize,
      });

      // Create a buffer that contains zeroes in the allowed access area, and 42s everywhere else.
      const testBuffer = t.makeBufferWithContents(
        new Uint8Array(expectedData),
        GPUBufferUsage.COPY_SRC |
          GPUBufferUsage.UNIFORM |
          GPUBufferUsage.STORAGE |
          GPUBufferUsage.COPY_DST
      );

      // Run the shader, accessing the buffer.
      runShaderTest(
        t,
        GPUShaderStage.COMPUTE,
        testSource,
        layout,
        [
          {
            binding: 0,
            resource: {
              buffer: testBuffer,
              offset: dynamicOffset ? 0 : bufferBindingOffset,
              size: bufferBindingSize,
            },
          },
        ],
        dynamicOffset ? [bufferBindingOffset] : undefined
      );

      // Check that content of the buffer outside of the allowed area didn't change.
      const expectedBytes = new Uint8Array(expectedData);
      t.expectGPUBufferValuesEqual(testBuffer, expectedBytes.subarray(0, bufferBindingOffset), 0);
      t.expectGPUBufferValuesEqual(
        testBuffer,
        expectedBytes.subarray(bufferBindingEnd, testBufferSize),
        bufferBindingEnd
      );
    } else {
      runShaderTest(t, GPUShaderStage.COMPUTE, testSource, layout, []);
    }
  });