emscripten-core / emscripten-core/emscripten

Bug with swab, unexpected result - fix

Open
#15,578 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

[swab.c](https://github.com/emscripten-core/emscripten/blob/f0c4614a279ff57ce331ba3bcb60b076ac171603/system/lib/libc/musl/src/string/swab.c)

I found this bug using a library in my webassembly project, after 2 days I found the source of the divergence.

This function swap the bytes, the problem is if compiled with any c++ compiler it produces the correct value, if compiled with Emscripten it produces the wrong value because during the swap it "doesn't remember" the original value before it has been replaced, so he copy 2 times the same value. I simply add a "tmp" value that stores the original value to be swapped.

```
void swab_fixed(const char* src, char * dest, size_t n)
{ uint8_t tmp;
for (; n > 1; n -= 2) {
tmp = dest[0];
dest[0] = src[1];
dest[1] = tmp;
dest += 2;
src += 2;
}
}
```

I enclosed a simple test you can verify the issue, compile both with emscripten and with your standard c++ compiler, you will notice the difference.
```
em++ test.cpp -o test.js
node test.js
```

test.cpp:
```
#include
#include

void swab_fixed(const char* src, char * dest, size_t n)
{ uint8_t tmp;
for (; n > 1; n -= 2) {
tmp = dest[0];
dest[0] = src[1];
dest[1] = tmp;
dest += 2;
src += 2;
}
}

bool check(uint16_t test) {

if (test != 344) {
printf("output is %d, not 344, Emscripten error!\n", test);
return false;
}
else printf("output is %d, OK!\n", test);
return true;
}

int main()
{
unsigned count = 1;
uint16_t * test = new uint16_t[count];
test[0] = 22529;

swab((char *) test, (char *) test, count * 2);
if (!check(test[0])) {
printf("Retrying with fixed swab...\n");
test[0] = 22529; swab_fixed((char *) test, (char *) test, count * 2);
check(test[0]);
}

delete[] test;
return 0;
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.