Skip to content

library_webgpu.js shim doesn't seem to support closure pass #20415

Closed as not planned

Description

@floooh

emsdk version 3.1.46

Building and running webgpu samples with webgpu.h works fine without the closure pass, but when trying to enable closure with the linker option --closure 1, linking appears to work, but when running I get the following errors on the browser js console:

Uncaught (in promise) TypeError: Failed to execute 'configure' on 'GPUCanvasContext': Failed to read the 'format' property from 'GPUCanvasConfiguration': Required member is undefined.
    at Da (triangle-sapp.js:54:9)
    at triangle-sapp.wasm:0x1165
    at triangle-sapp.wasm:0x1b7b
    at triangle-sapp.js:42:369
    at mc (triangle-sapp.js:27:301)
    at triangle-sapp.js:42:252
onerror: Uncaught TypeError: Failed to execute 'configure' on 'GPUCanvasContext': Failed to read the 'format' property from 'GPUCanvasConfiguration': Required member is undefined.

triangle-sapp.js:54 Uncaught TypeError: Failed to execute 'configure' on 'GPUCanvasContext': Failed to read the 'format' property from 'GPUCanvasConfiguration': Required member is undefined.
    at Da (triangle-sapp.js:54:9)
    at triangle-sapp.wasm:0x1165
    at triangle-sapp.wasm:0x3269
    at Object.lb (triangle-sapp.js:18:70)
    at b (triangle-sapp.js:11:46)

The JS file location triangle-sapp.js:54:9 looks like this:

Screenshot 2023-10-08 at 18 36 28

The only place in library_webgpu.js which has a configure call seems to be:

var configuration = {
"device": device,
"format": WebGPU.TextureFormat[
{{{ gpu.makeGetU32('descriptor', C_STRUCTS.WGPUSwapChainDescriptor.format) }}}],
"usage": {{{ gpu.makeGetU32('descriptor', C_STRUCTS.WGPUSwapChainDescriptor.usage) }}},
"alphaMode": "opaque",
};
context["configure"](configuration);

I don't know what's needed to make such a JS shim closure-compatible, e.g. whether there are generally some sort of annotations missing, or only in this specific location. I could probably help with investigation and fixing if I would know where to start :)

Cheers!

(cc: @kainino0x)

Activity

  1. changed the title [-]webgpu.js shim doesn't seem to support closure pass[/-] [+]library_webgpu.js shim doesn't seem to support closure pass[/+] on Oct 8, 2023
  2. kripken commented on Oct 9, 2023

    @kripken
    Member

    Maybe add a little logging - is the value sent into format undefined somehow? If the read on the typed array is out of bounds, it would be, but it does seem odd for closure to cause that... if it is undefined, comparing to a non-closure build could help.

    Otherwise, that code (both in the output and the source) seems ok.

    The only other idea I'd have is if the error is actually on the internals of that object send into device:, a (if it's expected to have a format field but doesn't - logging out that object might help).

  3. floooh commented on Oct 10, 2023

    @floooh
    CollaboratorAuthor

    I'll try to investigate, thanks for the hints!

  4. kainino0x commented on Oct 10, 2023

    @kainino0x
    Collaborator

    Most likely {{{ gpu.makeGetU32('descriptor', C_STRUCTS.WGPUSwapChainDescriptor.format) }}} -> z[c + 12 >> 2] is somehow producing a value that's either 0 or out of bounds of WebGPU.TextureFormat. This could be flaky if the C value was uninitialized, though I have no idea why this would be affected by Closure.

  5. floooh commented on Oct 11, 2023

    @floooh
    CollaboratorAuthor

    Hmm, the incoming WGPUSwapChainDescriptor looks correct (usage, width, height) except for the format which is 0.

    ...I'm getting that pixel format via wgpuSurfaceGetPreferredFormat, maybe this returns zero when closure is active, looking at that next...

  6. floooh commented on Oct 11, 2023

    @floooh
    CollaboratorAuthor

    I think I found the culprit... not sure yet why it happens. But:

    Closure-ized wgpuSurfaceGetPreferredFormat (

    wgpuSurfaceGetPreferredFormat: (surfaceId, adapterId) => {
    var format = navigator["gpu"]["getPreferredCanvasFormat"]();
    return WebGPU.PreferredFormat[format];
    },
    ) looks like this:

        qa: ()=>{
            var a = navigator.gpu.getPreferredCanvasFormat();
            return ob[a]
        }

    'var a' is 'bgra8unorm' which is then used as key on the ob object (which should be a mapping from string names to numbers), but the ob property names have been minified:

    image

    So ob['bgra8unorm'] would return undefined, because there's no property bgra8unorm on ob, because those have been minified by closure.

  7. floooh commented on Oct 11, 2023

    @floooh
    CollaboratorAuthor

    Hmm, those string-to-number mapping objects all look the same, I assume those are all affected by the minification, but the PreferredFormat is just the first one that's encountered:

    // Map from enum string back to enum number, for callbacks.
    DeviceLostReason: {
    'undefined': 0,
    'destroyed': 1,
    },
    PreferredFormat: {
    'rgba8unorm': 0x12,
    'bgra8unorm': 0x17,
    },
    BufferMapState: {
    'unmapped': 0,
    'pending': 1,
    'mapped': 2,
    },

    I guess those need to be annotated somehow so that closure leaves the keys alone. I'll see if I can find any similar mapping objects elsewhere and see how those are handled.

    PS: hmm apparently putting the property names into quotes should be enough to prevent closure minification... why doesn't this work? (PS: apparently only in 'ADVANCED' closure mode, I'll keep digging)

  8. floooh commented on Oct 11, 2023

    @floooh
    CollaboratorAuthor

    Ok I give up. I haven't found a way so far sneaking those string-to-number mappings past Closure.

    Apparently there's an undocumented tag /** @expose */, and there's also an official tag /** @export */. Either they don't work as I would expect, or maybe comments are removed before closure sees them.

    I also tried to create the mapping object differently like this:

        PreferredFormat: (() => {
          const map = {};
          map['rgba8unorm'] = 0x12;
          map['bgra8unorm'] = 0x17;
          return map;
        })(),

    ...also didn't seem to work.

    Halp!!1 :)

  9. kripken commented on Oct 11, 2023

    @kripken
    Member

    Interesting... I tested various combinations here:

    addToLibrary({
      $libA: {
        PreferredFormat: {
          'rgba8unorm': 0x12,
          'bgra8unorm': 0x17,
        },
      },
      $libB: {
        'rgba8unorm': 0x12,
        'bgra8unorm': 0x17,
      },
      $libC: function() {
        return {
          'rgba8unorm': 0x12,
          'bgra8unorm': 0x17,
        };
      }
    });

    Those show up in the output JS like this:

    var libA = {
     PreferredFormat: {
      rgba8unorm: 18,
      bgra8unorm: 23
     }
    };
    
    var libB = {
     rgba8unorm: 18,
     bgra8unorm: 23
    };
    
    function libC() {
     return {
      "rgba8unorm": 18,
      "bgra8unorm": 23
     };
    }

    So the first two are broken (missing ") while the last is ok. The last is by far the most common way we use quoted objects, that is, inside code and not on an object that is directly included itself, so I'd guess something in that direct inclusion path is going wrong. I'm investigating that now.

  10. floooh commented on Oct 11, 2023

    @floooh
    CollaboratorAuthor

    Hmm, one solution is to turn the mapping into a function:

        mapPreferredFormat: (fmt) => {
          switch (fmt) {
            case 'rgba8unorm': return 0x12;
            case 'bgra8unorm': return 0x17;
          }
        },

    ...this allows it to get past the swapchain creation.

    But then the next problem (and something entirely different) is in the wgpuDeviceGetLimits shim:

    wgpuDeviceGetLimits: (deviceId, limitsOutPtr) => {
    var device = WebGPU.mgrDevice.objects[deviceId].object;
    var limitsPtr = {{{ C_STRUCTS.WGPUSupportedLimits.limits }}};
    function setLimitValueU32(name, limitOffset) {
    var limitValue = device.limits[name];
    {{{ makeSetValue('limitsOutPtr', 'limitsPtr + limitOffset', 'limitValue', 'i32') }}};
    }
    function setLimitValueU64(name, limitOffset) {
    var limitValue = device.limits[name];
    {{{ makeSetValue('limitsOutPtr', 'limitsPtr + limitOffset', 'limitValue', 'i64') }}};
    }
    setLimitValueU32('maxTextureDimension1D', {{{ C_STRUCTS.WGPULimits.maxTextureDimension1D }}});
    setLimitValueU32('maxTextureDimension2D', {{{ C_STRUCTS.WGPULimits.maxTextureDimension2D }}});
    setLimitValueU32('maxTextureDimension3D', {{{ C_STRUCTS.WGPULimits.maxTextureDimension3D }}});
    setLimitValueU32('maxTextureArrayLayers', {{{ C_STRUCTS.WGPULimits.maxTextureArrayLayers }}});

    ...this gets minified to:

    ga: (a,b)=>{
            function c(g, h) {
                B[b + (8 + h) >> 2] = f.nb[g]
            }
            function d(g, h) {
                g = f.nb[g];
                Ga = [g >>> 0, (H = g,
                1 <= +Math.abs(H) ? 0 < H ? +Math.floor(H / 4294967296) >>> 0 : ~~+Math.ceil((H - +(~~H >>> 0)) / 4294967296) >>> 0 : 0)];
                B[b + (8 + h) >> 2] = Ga[0];
                B[b + (8 + h + 4) >> 2] = Ga[1]
            }
            var f = S.Wa[a].object;
            c("maxTextureDimension1D", 0);
            c("maxTextureDimension2D", 4);
            c("maxTextureDimension3D", 8);

    Note how the original code:

        function setLimitValueU32(name, limitOffset) {
          var limitValue = device.limits[name];
          {{{ makeSetValue('limitsOutPtr', 'limitsPtr + limitOffset', 'limitValue', 'i32') }}};
        }

    ...minified to:

            function c(g, h) {
                B[b + (8 + h) >> 2] = f.nb[g]
            }

    ...meaning .limits is now .nb!

    This might turn out to become a real rabbit hole...

  11. kripken commented on Oct 11, 2023

    @kripken
    Member

    Unfortunately the issue is due to how JS parsing and toString works:

    > x = (function a() { return { 'b': 5 } })
    [Function: a]
    > x.toString()
    "function a() { return { 'b': 5 } }"
    > y = { 'b': 5 }
    { b: 5 }
    > y.toString()
    '[object Object]'

    That is, JS engines keep a copy of the source JS for function, and toString() retrieves that including any quotation marks. But JS engines do not do that for objects, where the quotes are simply lost.

    A hard way to fix this would be to not use the JS engine native parsing and instead use Acorn, whose AST does note quoted properties. But that would mean integration Acorn in an entirely new part of Emscripten, and could make compilation slower.

    Another option might be to always quote object properties. But that would be excessive and increase code size.

    Other than that, we could work around this in library_webgpu using a function as @floooh said. That would also increase code size a little, but just here. That might be the best option if no one else has a better idea.

  12. floooh commented on Oct 11, 2023

    @floooh
    CollaboratorAuthor

    That last format seems to work if the shim is changed like this:

        PreferredFormat: () => {
          return {
            'rgba8unorm': 0x12,
            'bgra8unorm': 0x17,
          };
        },
        // ...
        wgpuSurfaceGetPreferredFormat: (surfaceId, adapterId) => {
          var format = navigator["gpu"]["getPreferredCanvasFormat"]();
          return WebGPU.PreferredFormat()[format];
        },

    ...interestingly Closure seems to turn that function into:

        qa: ()=>({
            rgba8unorm: 18,
            bgra8unorm: 23
        })[navigator.gpu.getPreferredCanvasFormat()],

    ...pretty crazy...

    PS: this works too:

        PreferredFormat: () => ({
          'rgba8unorm': 0x12,
          'bgra8unorm': 0x17,
        }),
  13. kripken commented on Oct 11, 2023

    @kripken
    Member

    ...meaning .limits is now .nb!

    If .limits arrives from the WebGPU API, then device.limits should be device['limits'] in library_webgpu.js.

  14. floooh commented on Oct 11, 2023

    @floooh
    CollaboratorAuthor

    Right. I guess somebody "just" needs to go through library_webgpu.js and fix all the little things.

    On my side, one problem is that I don't have an exhaustive test code base which calls all WebGPU functions (and thus would catch all problems), e.g. I could only fix the stuff that's called in my code base, and I'm only using a subset of the WebGPU feature set.

    But I can try to get my code working and provide a list of required changes (even if incomplete), or some sort of proposal PR.

  15. 22 remaining items

  16. floooh commented on Jul 31, 2024

    @floooh
    CollaboratorAuthor

    ...looking at the same code in the non-minified code now...

  17. floooh commented on Jul 31, 2024

    @floooh
    CollaboratorAuthor

    In the unminified code, the result of the HEAPU32 lookup HEAPU32[descriptor + 12 >> 2] is 23, and not 0 like in the minified version.

    But I just realized why I had such a strong deja-vu all the time. I had that all figured out already 😂

    #20415 (comment)

  18. floooh commented on Jul 31, 2024

    @floooh
    CollaboratorAuthor

    ...e.g. the problem are these mapping objects:

    // Map from enum string back to enum number, for callbacks.
    Int_BufferMapState: {
    'unmapped': 0,
    'pending': 1,
    'mapped': 2,
    },
    Int_CompilationMessageType : {
    'error': 0,
    'warning': 1,
    'info': 2,
    },
    Int_DeviceLostReason: {
    'undefined': 1,
    'unknown': 1,
    'destroyed': 2,
    },
    Int_PreferredFormat: {
    'rgba8unorm': 0x12,
    'bgra8unorm': 0x17,
    },

    ...if you follow the discussion starting at #20415 (comment) there are various potential solutions (for instance wrapping those mappings into functions) - e.g. the decimal 23 I'm seeing in the unminified version is that 0x17 in Int_PreferredFormat mapping.

  19. kainino0x commented on Apr 14, 2025

    @kainino0x
    Collaborator

    If there are any remaining issues in Emscripten's current WebGPU implementation, they won't be fixed, but emdawnwebgpu (see #23432) has been more thoroughly tested with Closure and should be working.

  20. floooh commented on Apr 15, 2025

    @floooh
    CollaboratorAuthor

    Oki doki, is it still planned to eventually upstream emdawnwebgpu into Emscripten?

  21. sbc100 commented on Apr 15, 2025

    @sbc100
    Collaborator

    No, I believe the plan is to remove webgpu from emscripten and have the port live externally.

  22. floooh commented on Apr 15, 2025

    @floooh
    CollaboratorAuthor

    Hmm, that will make integration harder, especially if this is still true (from https://source.chromium.org/chromium/chromium/src/+/main:third_party/dawn/src/emdawnwebgpu/README.md):

    Image

    There's this ticket though about unbundling from the Dawn repo (which is a 500 MBytes clone even without dependencies).

    https://issues.chromium.org/issues/371024051

    Personally I would very much prefer that WebGPU is handled the same as WebGL in the Emscripten SDK (e.g. webgpu.h plus libwebgpu.js shim).

    (at least after the WebGPU API has stabilized)

    PS: also when considering language bindings... for instance the Zig bindings for my C libraries currently only require the Emscripten SDK for headers and the link step and both WebGL and WebGPU builds out of the box. When WebGPU support is somewhere else that will just complicate things...

  23. sbc100 commented on Apr 15, 2025

    @sbc100
    Collaborator

    We are hoping to keep it very simple. I believe @kainino0x is making releases that you can point to and you certainly won't need to be clone the whole repo.

    In general I'm hoping to we can take some of the pressure off the emscripten repo by hosting more stuff like this externally.

  24. floooh commented on Apr 15, 2025

    @floooh
    CollaboratorAuthor

    Sounds like Emscripten needs a package manager ;)

    (e.g. would be kinda cool if there would be a quasi-standard for a 'C header plus JS shim' package format)

  25. sbc100 commented on Apr 15, 2025

    @sbc100
    Collaborator

    An yes, under the hood I believe its basically the same webgpu.h + libwebgpu.js but maintained upstream and packaged as an emscripten port.

  26. kainino0x commented on Apr 15, 2025

    @kainino0x
    Collaborator

    The plan is to maintain it fully outside Emscripten. We may add a builtin port to Emscripten (that downloads it for you) once it's a bit more stable. But for now it'll still be super easy as soon as I get the packaging/publishing up and running. I already have preview packages you can use, see here:

    #23432 (comment)

  27. floooh commented on Jun 11, 2025

    @floooh
    CollaboratorAuthor

    Confirmed working with emdawnwebgpu, thanks @kainino0x!

  28. floooh commented on Jun 14, 2025

    @floooh
    CollaboratorAuthor

    Ooooh.... correction, the problem is now back. I'm investigating and will write a ticket over at emdawnwebgpu.

  29. floooh commented on Jun 14, 2025

    @floooh
    CollaboratorAuthor

    For reference, followup ticket: https://issues.chromium.org/issues/424836759

    (the problem is missing items in the webgpu-externs.js file)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions