Skip to content

::dup2(fd, -1) does not return -1 or set errno #22040

@hly2019

Description

@hly2019

Please include the following in your bug report:

Version of emscripten/emsdk:
3.1.54

Failing command line in full:

# wasm:
emcc dup2.cpp -o main.js 
node main.js

# native:
g++ dup2.cpp -o main
./main

Hi, it seems the return value of int dup2(int oldfd, int newfd) is not correct and the errno is not set when the newfd is -1, as shown in the code and results below.

According to https://man7.org/linux/man-pages/man2/dup.2.html#RETURN_VALUE, dup2 should return -1 and set errno on error, and so it does with native execution.
But in wasm execution, the return value is not -1, and the errno is not set when the second argument, new_fd is -1. This issue may lead to problems with error checking.

I'd appreciate it so much if you could check it. Thanks!

Code:

Here shows the case I faced.
I also tried the case when the fd is got from calling ::open with a regular file (compiled with --preload-file), and the same problem also happens.

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main() {
    int fds[2];
    pipe(fds);
    int fd = fds[0];
    // int fd = ::open("temp.txt", O_RDWR); // compile with --preload-file temp.txt
    int ret = ::dup2(fd, -1); // the problem remains if here the fd is from ::open with regular file
    printf("ret of dup2: %d, error num: %d, error info: %s\n", ret, errno, strerror(errno));
    return 0;
}

Results:

In wasm, the errno is not set and the return value is also not -1, which is not as expected.

# in wasm:
ret of dup2: 5, error num: 0, error info: No error information

# in native:
ret of dup2: -1, error num: 9, error info: Bad file descriptor

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions