Memory Access Out of Bounds — WebGL
I was getting this error when I try to load my Web game:
My game is loaded at this domain: Highest Flavor Website Link This is my project settings at the time of build export:
Please give me some suggestion to solve this problem.
asked Mar 12, 2020 at 14:13
4,182 12 12 gold badges 47 47 silver badges 95 95 bronze badges
did you try what the popup says? open the browsers console and check the details of the error in there?
Mar 12, 2020 at 14:15
how to check the details? that I don’t know 🙁
Mar 12, 2020 at 14:17
it should be F12, then console. there it gives the details of the error.
Mar 12, 2020 at 14:20
I was getting this kind of exception — RuntimeError: memory access out of bounds,RuntimeError: memory access out of bounds
Mar 12, 2020 at 14:24
what does you game do on startup?
Mar 12, 2020 at 14:40
3 Answers 3
This error happened to me due to using the dynamic keyword. After replacing all my dynamic types with object the error was gone. Apparently the dynamic keyword is not supported on WebGL builds.
answered Sep 23, 2020 at 20:03
Endel Dreyer Endel Dreyer
1,644 18 18 silver badges 27 27 bronze badges
I’ve finally fixed the same error in my project. Here is what i did:
- Narrow down the line of code that crashes WebGL. Go through the painfull process of pinpointing the line of code that is the source of the error. I had this «luck» that error occured when I’ve hit button and tried to load UIScene in Addition mode. So at first I found the script in the scene which when disabled got rid of the crash. Then I’ve repeated the steps and digged deeper into lines. After 2 hours of builds, comments etc I’ve found that the code was not working was setting the new color for UnityEngine.UI.Image. Which was pretty weird because in playmode everything worked ok.
- Find solution. I think my solution might not be universal but I think there is something going in the Unity gameloop/lifecycle when running WebGL. The source of the problem was that i set the field that was storing my UI.Image in the Start method and then in some function I’ve tried to change the color.
Property was not exposed in inspector.
public class ModuleUI : MonoBehaviour < Image qualityBG; void Start() < qualityBG = GetComponent(); > .
then this line below was the cause of the crash
public void Set(Module module)
- Fixing — so I’ve added [SerializeField] attribute to the field and set it up in editor, dragged the Image into the inspector slot. An it fixed it. I suspect that WebGL build might perform some methods in different order, or maybe the multipleScene loaded together might to do with it. I’m not sure but the field was not set properly with previous code fot WebGL build.
Bonus: I’ve also fixed some issues that was not critical (not crushing WebGL game) but not working properly as expected in playmode. This also has got to do with trying to set some object in Start() method and then doing something on them. The collection was not set up (probably null) in WebGL.
EffectUI[] effects; Start() < effects = GetComponentsInChildren(); > void HideAllEffects()
And this also started working when I’ve added [SerializeField] to effects and hook it up in the scene.
Hope this will help some of you guys & gals!
How to fix Blazor WASM memory access out of bounds error?
Started a new Blazor WebAssembly project (Windows 10, Visual Studio 2019), trying to get a simple list via HttpClient from the server side. Error:
00755c3a:0xa3a0 Uncaught (in promise) RuntimeError: memory access out of bounds at malloc (:wasm-function[359]:0xa3a0) at monoeg_malloc (:wasm-function[161]:0x3c71) at stack_frag_new (:wasm-function[2019]:0x59758) at add_frag (:wasm-function[1430]:0x3ccf2) at interp_exec_method (:wasm-function[1120]:0x2f609) at interp_runtime_invoke (:wasm-function[5655]:0xf7391) at mono_jit_runtime_invoke (:wasm-function[5109]:0xddb3d) at do_runtime_invoke (:wasm-function[1410]:0x3ba85) at mono_runtime_try_invoke (:wasm-function[418]:0xcfdb) at mono_runtime_invoke (:wasm-function[1610]:0x44b39)
Server side (this returns properly):
[HttpGet] public async Task> Get()
client side: doesn’t render anything despite getting results back.
Profile Full Name Gender Age @foreach (var user in Users) < 
@user.FullName @user.Gender @user.Age > > @code < private IEnumerableUsers; string LoggedEmail; string UserId; string UserActionMessage = "No Logged User"; string Wanted = ""; protected async override Task OnInitializedAsync() < Users = await Http.GetFromJsonAsync("user"); > >
client project file:
netstandard2.1 3.0
server project file:
netcoreapp3.1
Would appreciate any help. Thanks. Edit: Models:
public class UserDetailsRM : IIntEntity < public int Id < get; set; >public int UserDetailsId < get; set; >public string UserId < get; set; >public string FirstName < get; set; >public string LastName < get; set; >public DateTime Birthdate < get; set; >public int UserGenderOptionId < get; set; >private string gender; public string Gender < get < return gender; >set < if (value == "1") gender = "Male"; else if (value == "2") gender = "Female"; else gender = "Other"; >> public string FullName < get < return $""; > set < FullName = value; >> public int Age < get < var today = DateTime.Today; var age = today.Year - Birthdate.Year; if (Birthdate.Date >today.AddYears(-age)) age--; return age; > > public string ProfileImageUrl < get; set; >>
RuntimeError: memory access out of bounds — gatsby development extremely slow
Developing on Gatsby has been over time significantly slowing down — at times taking up 20-30 seconds for the hot loader to refresh the page. After around 10-20 updates to a page — it eventually always runs into the following error below:
error UNHANDLED REJECTION RuntimeError: memory access out of bounds - source-map-consumer.js:335 BasicSourceMapConsumer._parseMappings [frontend]/[gatsby]/[react-hot-loader]/[source-map]/lib/source-map-consumer.js:335:44 - source-map-consumer.js:315 BasicSourceMapConsumer._getMappingsPtr [frontend]/[gatsby]/[react-hot-loader]/[source-map]/lib/source-map-consumer.js:315:12 - source-map-consumer.js:387 _wasm.withMappingCallback [frontend]/[gatsby]/[react-hot-loader]/[source-map]/lib/source-map-consumer.js:387:57 - wasm.js:95 Object.withMappingCallback [frontend]/[gatsby]/[react-hot-loader]/[source-map]/lib/wasm.js:95:11 - source-map-consumer.js:371 BasicSourceMapConsumer.eachMapping [frontend]/[gatsby]/[react-hot-loader]/[source-map]/lib/source-map-consumer.js:371:16 - source-node.js:87 Function.fromStringWithSourceMap [frontend]/[gatsby]/[react-hot-loader]/[source-map]/lib/source-node.js:87:24 - webpack.development.js:150 onSourceMapReady [frontend]/[gatsby]/[react-hot-loader]/dist/webpack.development.js:150:61 - next_tick.js:68 process._tickCallback internal/process/next_tick.js:68:7
Our site is has roughly 250+ static pages in /pages , and is programmatically building around 30 pages from *.yml files generated by netlify-cms . I suspect that it has something to do with sourcemaps becoming exceedingly large — a wild guess is that it may have something to do with what we’re doing in gatsby-node.js or cms.js for netlify-cms’ admin page — although I’m not sure where to start to begin debugging an issue like this. Any pointers would be greatly appreciated. A temporary solution we have implemented is changing Gatsby’s default source maps from cheap-module-eval-source-map to eval which has brought hot-module recompile times down from 4-6 to 1-2 seconds. However we would obviously prefer to have proper sourcemaps with sane performance.
// For local development, we disable proper sourcemaps to speed up // performance. if (stage === "develop") < config = < . config, devtool: "eval", >>
We have also recently rebased our forked gatsby-netlify-cms-plugin on v4.1.6 which contained the following notable improvements: https://github.com/gatsbyjs/gatsby/pull/15191 https://github.com/gatsbyjs/gatsby/pull/15591 This update has helped quite a bit. However, we’d ideally prefer to get our HMR compile times into the sub 500ms range WITH proper sourcemaps. gatsby-node.js
const path = require("path"); const fs = require("fs"); const remark = require("remark"); const remarkHTML = require("remark-html"); const fetch = require("node-fetch"); const _ = require("lodash"); const < assertResourcesAreValid, sortResourcesByDate, getFeaturedResources, >= require("./src/utils/resources-data"); const parseForm = require("./src/utils/parseEloquaForm"); const < ELOQUA_COMPANY, ELOQUA_USERNAME, ELOQUA_PASSWORD, >= require("./src/config-secure"); let elqBaseUrl; const MARKDOWN_FIELDS = [ "overviewContentLeft", "overviewContentRight", "assetContent", "content", ]; function fetchJson(url, options) < function checkResponse(res) < return new Promise(resolve => < if (res.ok) < resolve(res); >else < throw Error(`Request rejected with status $`); > >); > function getJson(res) < return new Promise(resolve =>< resolve(res.json()); >); > return fetch(url, options) .then(res => checkResponse(res)) .then(res => getJson(res)); > function fetchEloqua(url) < const base64 = new Buffer( `$\\$:$` ).toString("base64"); const auth = `Basic $`; return fetchJson(url, < headers: < Authorization: auth >>); > function getElqBaseUrl() < return new Promise(resolve => < if (elqBaseUrl) < resolve(elqBaseUrl); >else < return fetchEloqua("https://login.eloqua.com/id").then( (< urls >) => < const baseUrl = urls.base; elqBaseUrl = baseUrl; resolve(baseUrl); >); > >); > function getElqForm(baseUrl, elqFormId) < return fetchEloqua(`$/api/rest/2.0/assets/form/$`); > function existsPromise(path) < return new Promise((resolve, reject) => < return fs.exists(path, (exists, err) =>err ? reject(err) : resolve(exists) ); >); > function mkdirPromise(path) < return new Promise((resolve, reject) => < return fs.mkdir(path, err =>(err ? reject(err) : resolve())); >); > function writeFilePromise(path, data) < return new Promise((resolve, reject) => < return fs.writeFile(path, data, err =>(err ? reject(err) : resolve())); >); > exports.onPreBootstrap = () => < // Cache the eloqua base URL used to make Eloqua requests return new Promise(resolve => < getElqBaseUrl().then(() =>< resolve(); >); >); >; exports.onCreateWebpackConfig = (< stage, actions, plugins, loaders >) => < let config = < resolve: < modules: [path.resolve(__dirname, "src"), "node_modules"], >, plugins: [ plugins.provide(< // exposes jquery as global for the Swiftype vendor library jQuery: "jquery", // ideally we should eventually remove these and instead use // explicit imports within files to take advantage of // treeshaking-friendly lodash imports $: "jquery", _: "lodash", >), plugins.define(< CMS_PREVIEW: false, >), ], >; if (stage === "build-html") < config = < . config, module: < rules: [ < // ignore these modules which rely on the window global on build phase test: /jquery|js-cookie|query-string|tabbable/, use: loaders.null(), >, ], >, >; > actions.setWebpackConfig(config); >; exports.onCreateNode = (< node, actions >) => < const < createNode, createNodeField >= actions; const < elqFormId, happyHour, resourcesData >= node; const forms = []; if (resourcesData) < assertResourcesAreValid(resourcesData); const sortedResources = sortResourcesByDate(resourcesData); const featuredResources = getFeaturedResources(resourcesData); createNodeField(< name: "sortedResourcesByDate", node, value: sortedResources, >); createNodeField(< name: "featuredResources", node, value: featuredResources, >); > // Convert markdown-formatted fields to HTML MARKDOWN_FIELDS.forEach(field => < const fieldValue = node[field]; if (fieldValue) < const html = remark() .use(remarkHTML) .processSync(fieldValue) .toString(); createNodeField(< node, name: field, value: html, >); > >); function createFormFieldsNode(< elqFormId, nodeFieldName >) < return getElqBaseUrl() .then(baseUrl =>getElqForm(baseUrl, elqFormId)) .then(form => < createNodeField(< node, name: nodeFieldName, value: parseForm(form), >); return Promise.resolve(); >) .catch(err => < throw `Eloqua Form ID $- $`; >); > // Fetch main Eloqua form and attach to node referencing elqFormId if (elqFormId) < const mainForm = createFormFieldsNode(< elqFormId, nodeFieldName: "formFields", >); forms.push(mainForm); > // The main event landing page has two forms, the main form and a happy hour // form. This gets the happy hour form. if (happyHour && happyHour.elqFormId) < const happyHourForm = createFormFieldsNode(< elqFormId: happyHour.elqFormId, nodeFieldName: "happyHourFormFields", >); forms.push(happyHourForm); > return Promise.all(forms); >; exports.onCreatePage = (< page, actions >) => < const < createPage, deletePage >= actions; // Pass the page path to context so it's available in page queries as // GraphQL variables return new Promise(resolve => < const oldPage = Object.assign(<>, page); deletePage(oldPage); createPage(< . oldPage, context: < slug: oldPage.path, >, >); resolve(); >); >; exports.createPages = (< graphql, actions >) => < const dir = path.resolve("static/compiled"); const file = path.join(dir, "blocked-email-domains.json"); const lpStandardTemplate = path.resolve("src/templates/lp-standard.js"); const lpEbookTemplate = path.resolve("src/templates/lp-ebook.js"); const lpWebinarSeriesTemplate = path.resolve( "src/templates/lp-webinar-series.js" ); const lpThankYouTemplate = path.resolve("src/templates/lp-thank-you.js"); const lpEventMainTemplate = path.resolve("src/templates/lp-event-main.js"); const lpEventHappyHourTemplate = path.resolve( "src/templates/lp-event-happy-hour.js" ); const lpEventActivityTemplate = path.resolve( "src/templates/lp-event-activity.js" ); const lpEventRoadshowTemplate = path.resolve( "src/templates/lp-event-roadshow.js" ); const < createPage >= actions; return graphql(` < // a bunch of graphQL queries >`).then(result => < if (result.errors) < throw result.errors; >// Create pages from the data files generated by the CMS result.data.allLpStandardYaml.edges.forEach((< node >) => < createPage(< path: `resources/$`, component: lpStandardTemplate, context: < . node, >, >); >); result.data.allLpThankYouYaml.edges.forEach((< node >) => < createPage(< path: `resources/$`, component: lpThankYouTemplate, context: < . node, >, >); >); result.data.allLpEbookYaml.edges.forEach((< node >) => < createPage(< path: `resources/$`, component: lpEbookTemplate, context: < . node, >, >); >); result.data.allLpWebinarSeriesYaml.edges.forEach((< node >) => < createPage(< path: `resources/$`, component: lpWebinarSeriesTemplate, context: < . node, >, >); >); result.data.allLpEventMainYaml.edges.forEach((< node >) => < createPage(< path: `events/$`, component: lpEventMainTemplate, context: < . node, >, >); >); result.data.allLpEventHappyHourYaml.edges.forEach((< node >) => < createPage(< path: `events/$`, component: lpEventHappyHourTemplate, context: < . node, >, >); >); result.data.allLpEventActivityYaml.edges.forEach((< node >) => < createPage(< path: `events/$`, component: lpEventActivityTemplate, context: < . node, >, >); >); result.data.allLpEventRoadshowYaml.edges.forEach((< node >) => < createPage(< path: `events/$`, component: lpEventRoadshowTemplate, context: < . node, >, >); >); // Build copy of blocked-email-domains.yml as JSON in /static // This is referenced by the Eloqua-hosted forms on go.memsql.com const < blockedEmailDomains >= result.data.miscYaml; const domainsArray = blockedEmailDomains .trim() .split("\n") .map(rule => rule.toLowerCase()); return existsPromise(dir) .then(exists => (exists ? Promise.resolve() : mkdirPromise(dir))) .then(() => writeFilePromise(file, JSON.stringify(domainsArray))); >); >;
package.json
< . "browserslist": [ ">0.25%", "not dead" ], "devDependencies": < "@babel/core": "7.1.5", "@babel/plugin-syntax-dynamic-import": "7.2.0", "@storybook/addon-knobs": "5.0.11", "@storybook/addon-storysource": "5.0.11", "babel-eslint": "8.2.2", "babel-loader": "8.0.4", "eslint": "4.12.1", "eslint-plugin-babel": "4.1.2", "eslint-plugin-flowtype": "2.39.1", "eslint-plugin-import": "2.8.0", "eslint-plugin-prettier": "2.3.1", "eslint-plugin-react": "7.5.1", "file-loader": "2.0.0", "gatsby": "2.8.8", "gatsby-link": "2.1.1", "gatsby-plugin-intercom-spa": "0.1.0", "gatsby-plugin-netlify-cms": "vai0/gatsby-plugin-netlify-cms#918821c", "gatsby-plugin-polyfill-io": "1.1.0", "gatsby-plugin-react-helmet": "3.0.12", "gatsby-plugin-root-import": "2.0.5", "gatsby-plugin-sass": "2.1.0", "gatsby-plugin-sentry": "1.0.1", "gatsby-plugin-sitemap": "2.1.0", "gatsby-source-apiserver": "2.1.2", "gatsby-source-filesystem": "2.0.39", "gatsby-transformer-json": "2.1.11", "gatsby-transformer-yaml": "2.1.12", "html-webpack-plugin": "3.2.0", "node-fetch": "2.3.0", "node-sass": "4.12.0", "react-lorem-component": "0.13.0", "remark": "10.0.1", "remark-html": "9.0.0", "uglify-js": "3.3.28", "uglifyjs-folder": "1.5.1", "yup": "0.24.1" >, "dependencies": < "@fortawesome/fontawesome-pro": "5.6.1", "@fortawesome/fontawesome-svg-core": "1.2.6", "@fortawesome/free-brands-svg-icons": "5.5.0", "@fortawesome/pro-regular-svg-icons": "5.4.1", "@fortawesome/pro-solid-svg-icons": "5.4.1", "@fortawesome/react-fontawesome": "0.1.3", "@storybook/addon-a11y": "5.0.11", "@storybook/addon-viewport": "5.0.11", "@storybook/addons": "5.0.11", "@storybook/cli": "5.0.11", "@storybook/react": "5.0.11", "anchorate": "1.2.3", "autoprefixer": "8.3.0", "autosuggest-highlight": "3.1.1", "balance-text": "3.3.0", "classnames": "2.2.5", "flubber": "0.4.2", "focus-trap-react": "4.0.0", "formik": "vai0/formik#d524e4c", "google-map-react": "1.1.2", "jquery": "3.3.1", "js-cookie": "2.2.0", "lodash": "4.17.11", "minisearch": "2.0.0", "moment": "2.22.0", "moment-timezone": "0.5.23", "netlify-cms": "2.9.0", "prop-types": "15.6.2", "query-string": "5.1.1", "react": "16.6.1", "react-add-to-calendar-hoc": "1.0.8", "react-anchor-link-smooth-scroll": "1.0.12", "react-autosuggest": "9.4.3", "react-dom": "16.6.1", "react-helmet": "5.2.0", "react-player": "1.7.0", "react-redux": "6.0.0", "react-remove-scroll-bar": "1.2.0", "react-select": "1.2.1", "react-slick": "0.24.0", "react-spring": "6.1.8", "react-truncate": "2.4.0", "react-typekit": "1.1.3", "react-waypoint": "8.0.3", "react-youtube": "7.6.0", "redux": "4.0.1", "slick-carousel": "1.8.1", "typeface-inconsolata": "0.0.54", "typeface-lato": "0.0.54", "whatwg-fetch": "2.0.4", "xr": "0.3.0" >>
import CMS from "netlify-cms"; import "typeface-lato"; import "typeface-inconsolata"; import "scss/global.scss"; import StandardLandingPagePreview from "cms/preview-templates/StandardLandingPagePreview"; import StandardThankYouPagePreview from "cms/preview-templates/StandardThankYouPagePreview"; import EbookLandingPagePreview from "cms/preview-templates/EbookLandingPagePreview"; import WebinarSeriesLandingPagePreview from "cms/preview-templates/WebinarSeriesLandingPagePreview"; import EventMainLandingPagePreview from "cms/preview-templates/EventMainLandingPagePreview"; import EventHappyHourLandingPagePreview from "cms/preview-templates/EventHappyHourLandingPagePreview"; import EventActivityLandingPagePreview from "cms/preview-templates/EventActivityLandingPagePreview"; import EventRoadshowLandingPagePreview from "cms/preview-templates/EventRoadshowLandingPagePreview"; // The following window and global config settings below were taken from here. // https://github.com/gatsbyjs/gatsby/blob/master/docs/docs/visual-testing-with-storybook.md // They're required because the netlify-cms runs on a separate webpack config, // and outside of Gatsby. This ensures any Gatsby components imported into the // CMS works without errors // highlight-start // Gatsby's Link overrides: // Gatsby defines a global called ___loader to prevent its method calls from creating console errors you override it here global.___loader = < enqueue: () =><>, hovering: () => <>, >; // Gatsby internal mocking to prevent unnecessary errors global.__PATH_PREFIX__ = ""; // This is to utilized to override the window.___navigate method Gatsby defines and uses to report what path a Link would be taking us to window.___navigate = pathname => < alert(`This would navigate to: https://www.memsql.com$`); >; CMS.registerPreviewTemplate("lp-standard", StandardLandingPagePreview); CMS.registerPreviewTemplate("lp-ebook", EbookLandingPagePreview); CMS.registerPreviewTemplate( "lp-webinar-series", WebinarSeriesLandingPagePreview ); CMS.registerPreviewTemplate("content", StandardLandingPagePreview); CMS.registerPreviewTemplate("content-syndication", StandardLandingPagePreview); CMS.registerPreviewTemplate("programmatic", StandardLandingPagePreview); CMS.registerPreviewTemplate("sponsored-webcast", StandardLandingPagePreview); CMS.registerPreviewTemplate("webcast", StandardLandingPagePreview); CMS.registerPreviewTemplate("web-forms", StandardLandingPagePreview); CMS.registerPreviewTemplate("other", StandardLandingPagePreview); CMS.registerPreviewTemplate("lp-thank-you", StandardThankYouPagePreview); CMS.registerPreviewTemplate("lp-event-main", EventMainLandingPagePreview); CMS.registerPreviewTemplate( "lp-event-happy-hour", EventHappyHourLandingPagePreview ); CMS.registerPreviewTemplate( "lp-event-activity", EventActivityLandingPagePreview ); CMS.registerPreviewTemplate( "lp-event-roadshow", EventRoadshowLandingPagePreview );
Environment
System: OS: Linux 4.19 Debian GNU/Linux 10 (buster) 10 (buster) CPU: (8) x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz Shell: 5.0.3 - /bin/bash Binaries: Node: 10.15.3 - ~/.nvm/versions/node/v10.15.3/bin/node Yarn: 1.17.3 - /usr/bin/yarn npm: 6.9.0 - ~/.nvm/versions/node/v10.15.3/bin/npm Languages: Python: 2.7.16 - /usr/bin/python Browsers: Chrome: 75.0.3770.142 Firefox: 60.8.0 npmPackages: gatsby: 2.10.4 => 2.10.4 gatsby-cli: 2.7.2 => 2.7.2 gatsby-link: 2.2.0 => 2.2.0 gatsby-plugin-intercom-spa: 0.1.0 => 0.1.0 gatsby-plugin-manifest: 2.1.1 => 2.1.1 gatsby-plugin-netlify-cms: vai0/gatsby-plugin-netlify-cms#e92ec70 => 4.1.6 gatsby-plugin-polyfill-io: 1.1.0 => 1.1.0 gatsby-plugin-react-helmet: 3.1.0 => 3.1.0 gatsby-plugin-root-import: 2.0.5 => 2.0.5 gatsby-plugin-sass: 2.1.0 => 2.1.0 gatsby-plugin-sentry: 1.0.1 => 1.0.1 gatsby-plugin-sitemap: 2.2.0 => 2.2.0 gatsby-source-apiserver: 2.1.3 => 2.1.3 gatsby-source-filesystem: 2.1.0 => 2.1.0 gatsby-transformer-json: 2.2.0 => 2.2.0 gatsby-transformer-yaml: 2.2.0 => 2.2.0 npmGlobalPackages: gatsby-dev-cli: 2.5.0
Update: Here is a profile of a HMR — making a change, saving, undoing that change, then saving again. The compile time for this was around 1300ms for each change. Note this is with us setting sourcemaps in development to eval — the cheaper option. Anyone see anything that we can do to improve this time? It appears graphql is recompiling our queries even though our change is literally updating text. Here’s the performance profile result using Chrome Devtools.
Uncaught runtimeerror memory access out of bounds как исправить
I have successfully compiled stb_dxt, a DXT texture compressor written in C++, to emscripten and asm.js. This works wonderfully in Firefox but performance in Chrome is poor. I am therefore attempti.
I have successfully compiled stb_dxt , a DXT texture compressor written in C++, to emscripten and asm.js . This works wonderfully in Firefox but performance in Chrome is poor. I am therefore attempting to compile the same program to WebAssembly using the following flags:
emcc -O3 stb_dxt.cpp -o dxt.js -s DISABLE_EXCEPTION_CATCHING=1 -s NO_FILESYSTEM=1 -s EXPORTED_FUNCTIONS=»[‘_rygCompress’]» -s WASM=1 -s ALLOW_MEMORY_GROWTH=1
My Javascript glue code, which works perfectly with asm.js , needs to pass in an image ArrayBuffer like so:
this.width = input.width; this.height = input.height; this.srcSize = input.data.length*input.data.BYTES_PER_ELEMENT; this.inputPtr = STB.Module._malloc(this.srcSize); this.outputPtr = STB.Module._malloc(Math.max(8, this.srcSize/8)); this.inputHeap = new Uint8Array(STB.Module.HEAPU8.buffer, this.inputPtr, this.srcSize); this.outputHeap = new Uint8Array(STB.Module.HEAPU8.buffer, this.outputPtr, Math.max(8, this.srcSize/8)); //set inputHeap to jpeg decoded RGBA data this.inputHeap.set(input.data);
As you can see I am using _malloc to allocate the memory for the passed in ArrayBuffer and also for what will be the resulting output ArrayBuffer once the program has run and compressed the texture to DXT1.
However, as soon as the first call to _malloc fires, I am getting an out of bounds memory error:
Uncaught (in promise) RuntimeError: memory access out of bounds at ([24]+7062) at Object.Module._malloc
I assume that I’m doing something wrong, any help would be greatly appreciated.
The code I am trying to compile is available here: https://github.com/nothings/stb/blob/master/stb_dxt.h
My first guess is that wasm startup is async, and perhaps you’re calling into compiled code too early? Building with -s ASSERTIONS=1 -s SAFE_HEAP=1 might find something.
(Otherwise, all those options and that code should work identically on asm.js and wasm, nothing seems wrong there.)
Also worth checking if -s BINARYEN_ASYNC_COMPILATION=0 changes things.
Thanks for the quick response, it’s nearly 1am here. I’ll give your suggestions a try in the morning and let you know how I get on.
@kripken — I’ve tried compiling with the flags you suggested and I now get a series of memory enlargement related errors:
Module.reallocBuffer: Attempted to grow from 16777216 bytes to 134217728 bytes, but got error: RangeError: WebAssembly.Memory.grow(): maximum memory size exceeded
Failed to grow the heap from 16777216 bytes to 134217728 bytes, not enough memory!
failed to set errno from JS
wasm-00010efe-24:3754 Uncaught (in promise) RuntimeError: memory access out of bounds at ([24]+7062)
I forgot to mentioned previously, but once I have compiled the program and first run it, I get the following error:
WebAssembly Instantiation: memory import 10 has no maximum limit, expected at most 4294967295
It would appear that WebAssembly has recently changed their instantiation method to require the previously optional «maximum» option to be present.
Therefore, I am manually adding this option into the resulting javascript file following compilation:
Module["wasmMemory"]=new WebAssembly.Memory();
Perhaps this has something to do with it? However, my understanding was this that was only for the WebAssembly instantiation, and was not in any way related to the amount of memory that a compiled program can use, which should be grown internally as it runs.
Perhaps there have been some breaking changes recently?
Interestingly, if I divide the amount of memory I am trying to allocate by WebAssembly’s page size, the call to _malloc works:
var WASM_PAGE_SIZE = 65536; this.srcSize = input.data.length * input.data.BYTES_PER_ELEMENT / WASM_PAGE_SIZE ; this.inputPtr = STB.Module._malloc(this.srcSize);
But then of course, when I then create the Uint8Array() view and try to set the data, the buffer isn’t large enough.
Why should the _malloc call fail when I pass in the true length of the input data in bytes? (67108864)
I’ve managed to fix my issue by doing the following:
- Compiling with -s TOTAL_MEMORY=512MB
- Manually editing the javascript as follows:
Module["wasmMemory"]=new WebAssembly.Memory();
Everything then works, but sadly performance is far worse than compiling to asm.js .
- In Firefox nightly running my program goes from 450ms in asm.js, to around 3,500ms.
- In Chrome Canary, is goes from 1500ms to 3,800ms.
Is there anything I can do to improve this? Or is it simply down to the fact that WebAssembly isn’t optimized to the level of asm.js yet?
The BINARYEN_MEM_MAX option might help those build issues. Although things should work without it too, so something’s gone wrong, but I don’t remember all the details here to know what offhand — this went through a few revisions.
About perf, that is very surprising. It’s just the wasm flag changed between those? Can you put up links to asm.js and wasm versions, built with —profiling , so we can reproduce? If it does reproduce, we should file bugs on browsers, although if it makes both of those browsers slower, perhaps it’s our fault in the toolchain somehow.
@kripken — After a few hours of profiling and tweaking I have been able to improve on performance to the point where the WASM version is now significantly faster then the asm.js one, in Chrome. Firefox is still slightly faster when using asm.js however. Regardless, it seems that setting the input buffer in Chrome was causing a huge bottleneck for me but witching to Uint32Array views over the input ArrayBuffer made the copy far faster and solved it.
So this is great news, but still, I have to manually edit and include a maximum property in the javascript that’s output by Emscripten.
It would appear that WebAssembly has recently changed their instantiation method to require the previously optional «maximum» option to be present.
Do you have more info about this? I believe maximum should still be optional?
Do you have more info about this? I believe maximum should still be optional?
The only info I can give you is that without the maximum option being explicitly stated, compilation fails for me, giving a memory import 10 has no maximum limit error. The second I provide the option and set it to the same as the already present initial value, the error goes away and everything works.
This is using the latest incoming build of Emscripten… Sorry I can’t be any more help.
Very strange. We need a full testcase to diagnose this, I think, I’m not sure where things are going wrong.
We’re also experiencing rare errors like this sometimes at Figma, but only in Chrome (not Firefox). I logged a bug with Chrome before I found this issue.
I finally got SAFE_HEAP working. I verified that SAFE_HEAP works by making sure *(char*)0x3FFFFFFF triggers the heap checks (in both Firefox and Chrome). I then ran Figma with SAFE_HEAP enabled and no heap checks were triggered (in both Firefox and Chrome) but Firefox loaded fine and Chrome threw «memory access out of bounds». Does this mean the bug is in Chrome and not in emscripten? Is there anything else I should try?
I’m pretty sure it’s a Chrome bug at this point, yeah. One last thing I’d try is to build with -s DETERMINISTIC=1 which removes timing and randomness out of the picture. Also can’t hurt to add ASSERTIONS .
ASSERTIONS was a good idea. It looks like this is the problem:
Module.reallocBuffer: Attempted to grow from 1073741824 bytes to 1342177280 bytes, but got error: RangeError: WebAssembly.Memory.grow(): maximum memory size exceeded
Firefox allows the memory to grow over 1gb while Chrome doesn’t. Figma sometimes needs more than 1gb of memory for large documents. Is the 1gb limit something that emscripten sets? Or is this a limitation of Chrome’s implementation in particular?
I saw your comment above about BINARYEN_MEM_MAX so I tried -s BINARYEN_MEM_MAX=2147418112 but Chrome still fails to grow to 1342177280.
Interesting. Looks like a chrome bug, emscripten doesn’t set a 1GB limit (and it wouldn’t be browser-specific in any case). Let’s maybe move the discussion back to the chromium bug tracker to make sure they see it.
Another thought here (not relevant to the Chrome side, so not posting in the bug there): in Chrome the allocation failed, so your app should have seen malloc/new return NULL. Does that happen properly for you, or is emscripten messing that up somehow?
(That’s assuming you have ABORTING_MALLOC turned off, which I think is the case? Otherwise it should have called abort and halted the app.)
The crash is actually in malloc, not in our code. The call to malloc is still executing (i.e. at the top of the call stack) when the crash occurs so it never has the chance to return null. Here’s what the stack trace looks like:
Uncaught RuntimeError: memory access out of bounds at ([331 (_malloc)]+4483) at ([703 (_malloca)]+138) at ([714 (operator new(unsigned int))]+9) at ([6072 (Codec::encodePhaseAndPropertyChanges(MultiplayerMessage const&, Fig::Message&))]+772) at ([6070 (Codec::toBuffer(MultiplayerMessage const&, MessageFormat))]+1135) at ([6069 (MultiplayerMessage::toBuffer(ImageMode, MessageFormat) const)]+197) .
For what it’s worth, I did verify that we aren’t get any calls to malloc returning NULL before the crash.
I think I’ve figured it out. We #define MALLOC_ALIGNMENT 16 before dlmalloc.cpp. This is supposed to be safe:
MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *)) Controls the minimum alignment for malloc'ed chunks. It must be a power of two and at least 8, even on machines for which smaller alignments would suffice. It may be defined as larger than this though. Note however that code and data structures are optimized for the case of 8-byte alignment.
Calling malloc crashes in Chrome if we #define MALLOC_ALIGNMENT 16 but doesn’t crash if we #define MALLOC_ALIGNMENT 8 (the default). Any idea why this might be?
Scratch that, never mind. That just lets us load the app in barely under 1gb. We still have the same problem if I make the document slightly bigger.
Yeah, that crashing in malloc is definitely a sign of a problem in emscripten. I debugged it and found the issues, fixes and details in #5289.
Should be fixed by that merged PR.
I’m also experiencing this error when my program runs for a few minutes in Chrome
Uncaught RuntimeError: memory access out of bounds
at wasm-function[79]:46
at wasm-function[401]:379
at wasm-function[992]:1112
at wasm-function[338]:533
at wasm-function[1253]:704
at wasm-function[748]:707
at wasm-function[1378]:245
at wasm-function[1348]:205
at wasm-function[1356]:9
@Y0QIN — that might be a different issue, as I think the one here was fixed. To debug it, I’d start with building with -g so that stack trace is readable, and then hopefully what’s going wrong can be figured out. If not, if you can share a testcase we can debug that here.
added a commit
to surikov/riffshare
that referenced
this issue
Hi, I am trying to get my Unity LEGO microgame uploaded to play.unity.com.
I can build to WebGL and it uploads the game, but when I try to play it in my browser (chrome) it gives the following error:
‘An error occured running the Unity content on this page. See your browser Javascript console for more info. the error was: Uncaught RuntimeError: memory access out of bounds.’
You can try it here for yourself: https://play.unity.com/mg/lego/web-0osz7
I thought maybe the game was too heavy so I tried stripping the whole game down until there was barely anything left, but it still gives the same error when playing the uploaded build.
Edit: stripping down the game seems to work, I think I will have to rebuild and reupload untill I hit the maximum…
The chrome console shows these errors:
Uncaught RuntimeError: memory access out of bounds at :wasm-function[39464]:0xe48aa0 at :wasm-function[39463]:0xe48a33 at :wasm-function[39462]:0xe489c9 at :wasm-function[49594]:0x10a110c at :wasm-function[49601]:0x10a1f8f at :wasm-function[49599]:0x10a1a95 at :wasm-function[49598]:0x10a181f at :wasm-function[25339]:0xb97bac at dynCall_iiiii (:wasm-function[52471]:0x111f01b) at Object.dynCall_iiiii (blob:https://play.unity3dusercontent.com/08f085a7-7fd5-42f4-a591-d067454a8d6a:8:463265) at invoke_iiiii (blob:https://play.unity3dusercontent.com/08f085a7-7fd5-42f4-a591-d067454a8d6a:8:331727) at :wasm-function[50596]:0x10c8f11 at :wasm-function[50050]:0x10b0ed8 at :wasm-function[4469]:0x1b7b8d at :wasm-function[4467]:0x1b7865 at :wasm-function[8137]:0x2f5ff6 at :wasm-function[8134]:0x2f4e18 at :wasm-function[10603]:0x40081f at :wasm-function[8402]:0x3162cc at :wasm-function[10989]:0x42cea0 at :wasm-function[10703]:0x40a3f0 at :wasm-function[10703]:0x40a405 at :wasm-function[10698]:0x409f0f at :wasm-function[10691]:0x408112 at dynCall_v (:wasm-function[52485]:0x111f24d) at Object.dynCall_v (blob:https://play.unity3dusercontent.com/08f085a7-7fd5-42f4-a591-d067454a8d6a:8:471234) at browserIterationFunc (blob:https://play.unity3dusercontent.com/08f085a7-7fd5-42f4-a591-d067454a8d6a:8:166325) at Object.runIter (blob:https://play.unity3dusercontent.com/08f085a7-7fd5-42f4-a591-d067454a8d6a:8:169386) at Browser_mainLoop_runner (blob:https://play.unity3dusercontent.com/08f085a7-7fd5-42f4-a591-d067454a8d6a:8:167848)
Многие пользователи ПК во время работы с какой-либо программой могут столкнуться с «вылетом» указанной программы, и появившимся сообщением «Out of memory». Возникшая проблема может иметь множество причин, начиная от банального недостатка памяти на пользовательском ПК, и заканчивая некорректной работой с памятью какой-либо программы.
- Причины появления дисфункции
- Как исправить ошибку «Out of memory»
- Заключение

Причины появления дисфункции
Сообщение «Out of memory» (в переводе дословно «вне памяти», или «недостаточно памяти») обычно возникает при недостатке памяти на пользовательском компьютере. В частности же, в появлении данной ошибки «виновен» следующий набор факторов:
- Недостаток памяти RAM на вашем ПК (рабочей памяти, планки которой установлены на материнской плате вашего компьютера). Если на вашем компьютере установлен всего 1 гигабайт памяти, вы будете встречаться с описываемой ошибкой довольно часто. Нормальным же ныне считается наличие на компьютере 4 гигабайт памяти и выше;
- Недостаток места на жёстком диске.
Когда вашему компьютеру не хватает физической R.A.M. памяти, он заимствует часть места на жёстком диске, и создаёт так называемую «виртуальную память». Система временно хранит в такой виртуальной памяти ту часть данных, которая не помещается в памяти обычной. Такие данные обычно хранятся в файле «pagefile.sys», размер которого может увеличиваться или уменьшаться в зависимости от специфики работы вашей ОС. Если на диске будет недостаточно места, файл «pagefile.sys» не сможет расти, и пользователь получит рассматриваемую ошибку.

- При одновременном запуске на ПК большого количества программ, каждая из которых бронирует часть памяти ПК под свои задачи;
- При запуск большого количества вкладок браузера. Веб-навигаторы уровня «Firefox» или «Google Chrome» способны занимать от 500 мегабайт до 1 гигабайта памяти под свой функционал, при этом число открытых вкладок и соответствующей обслуживающей памяти может быть ограничено системой. Специалисты Майрософт называют такую проблему «the desktop heap limitation» — «ограничение кучи рабочего стола»);
- Некорректная работа с памятью ряда программ (наиболее часто это игровые программы);
- Не оптимальный размер файла подкачки, с которым работает система.
Как исправить ошибку «Out of memory»
Для решения указанной проблемы рекомендую сделать следующее:

- Перезагрузите ваш ПК, и запустите требуемую программу вновь. Возможно, что проблема имеет случайный характер, и более повторяться не будет;
- Перед запуском нужной программы закройте другие ненужные программы (браузер, музыкальный или видео плеер, текстовый или графический редактор, мессенджер и так далее);
- Если проблема возникает во время серфинга в сети, закройте всё множество вкладок вашего браузера (при наличии), оставив лишь одну или две.
Альтернативным вариантом решения проблемы является установка соответствующего фикса от Майкрософт. Или использование расширений или дополнений для браузера уровня «The Great Suspender» для «Google Chrome», хорошо работающего с ненужными вкладками браузера.

- Добавьте оперативной памяти на ваш ПК. Если у вас на компьютере установлено 1-2 гигабайта памяти, будет оптимальным довести её объём до 4 гигабайт (а для 64-битных Виндовс 7, 8 и 10 версии рекомендую 8 и более гигабайт);
- Убедитесь, что на вашем жёстком диске (или SSD) достаточно свободного места. При необходимости, освободите диск от ненужных файлов;
- Используйте инструмент командной строки BCDEdit для изменения параметров загрузки системы. Если у вас на ПК установлена Виндовс 7 и более, запустите командную строку от имени администратора на Виндовс 7 и Виндовс 10, и в ней наберите:
bcdedit/set IncreaseUserVa 3072
И нажмите на ввод, и перезагрузите ваш ПК. Функционал данной команды позволяет выделить пользовательским приложениям 3 гигабайта оперативной памяти для работы. В некоторых системах этого может быть слишком много, потому если после ввода данной команды система начала чаще сбоить, то введите в командной строке от имени администратора:
bcdedit /set IncreaseUserVa 2560 — что позволит задействовать 2,5 гигабайта вместо ранее забронированных 3.
Если ситуацию этим исправить не удалось, верните настройки на состояние по умолчанию:
bcdedit /deletevalue IncreaseUserVa
- Увеличьте объём файла подкачки. Нажмите кнопку «Пуск», в строке поиска введите sysdm.cpl и нажмите ввод. В открывшемся окне настроек системы выберите «Дополнительно» — «Быстродействие» — «Параметры» — «Дополнительно» — «Виртуальная память» — «Изменить». Снимите галочку с опции автоматического размера, поставьте галочку на «Указать размер», и поставьте исходный размер в 8192, и максимальный в 8192. Затем выберите «Задать»;

Установите нужный размер файла подкачки
Заключение
Ошибка «Out of memory» может иметь множество причин, связанных как с физическим недостатком памяти на ПК, так и другими детерминантами, изложенными мной выше. Для решения проблемы советую закрыть ненужные программы (вкладки браузера) на вашем компьютере (тем самым разгрузив его память), а самым эффективным инструментом является установка дополнительной планки памяти на ПК, что в большинстве случаев поможет избавиться от ошибки на вашем компьютере.