Skip to content

Working around a problem with msvcrt and setlocale #459

@m417z

Description

@m417z

I wrote here in detail about a nasty problem I encountered with msvcrt: llvm/llvm-project#110954

The short version is that if allocation fails while calling setlocale, which may happen in Windows during process shutdown regardless of memory availability, msvcrt shows a message box and terminates the process, both of which are pretty bad.

I'm not sure how the libc++ maintainers will react to the issue I created, I won't be surprised if they'll decide it's out of scope and an msvcrt problem. Since this toolchain is designed to work with msvcrt, perhaps a workaround can be added in the toolchain or its version of libc++. For example, setlocale can be wrapped by something like:

char* setlocale_wrapper(int category, const char* locale) {
  _ptiddata ptd = _getptd_noexit();
  return ptd ? setlocale(category, locale) : NULL;
}

Unfortunately _getptd_noexit isn't exported by msvcrt, so the actual implementation must be different.
_get_errno always returns ENOMEM in this case, and _set_errno always fails with ENOMEM, so an actual implementation can be:

char* setlocale_wrapper(int category, const char* locale) {
  errno_t err;
  if (_get_errno(&err) == 0 && err == ENOMEM && _set_errno(err) == ENOMEM) {
    return NULL;
  }
  return setlocale(category, locale);
}

It's not the most elegant solution but it solves a real problem.

What do you think? Any other ideas?

Thanks, and thank you for this project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions