Skip to content

Instantly share code, notes, and snippets.

@jkrems
Last active August 11, 2017 09:07
Show Gist options
  • Save jkrems/9869594 to your computer and use it in GitHub Desktop.
Save jkrems/9869594 to your computer and use it in GitHub Desktop.
Weird crashes when the tty init is moved out of main().

Works as expected:

gcc tty_crash.cc -I deps/libuv/include -L deps/libuv/out/Debug -luv && ./a.out

Crashes with various errors, bus errors/segmentation faults/SIGABRT:

gcc tty_crash.cc -I deps/libuv/include -L deps/libuv/out/Debug -luv -D CRASHING && ./a.out

According to gdb it's crashing on the QUEUE_REMOVE line in unix/stream.c:

static void uv__write_callbacks(uv_stream_t* stream) {
  uv_write_t* req;
  QUEUE* q;

  while (!QUEUE_EMPTY(&stream->write_completed_queue)) {
    /* Pop a req off write_completed_queue. */
    q = QUEUE_HEAD(&stream->write_completed_queue);
    req = QUEUE_DATA(q, uv_write_t, queue);
    QUEUE_REMOVE(q); // <-- here
    uv__req_unregister(stream->loop, req);
#include <uv.h>
void ttyThing(uv_loop_t *loop)
{
// exact copy of the code in main()
uv_tty_t tty;
uv_tty_init(loop, &tty, 1, 0);
uv_write_t req;
uv_buf_t buf;
buf.base = (char*) "Hello TTY\n";
buf.len = strlen(buf.base);
uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL);
uv_tty_reset_mode();
}
int main(int argc, const char *argv[])
{
uv_loop_t *loop = uv_default_loop();
#ifdef CRASHING
ttyThing(loop);
#else
uv_tty_t tty;
uv_tty_init(loop, &tty, 1, 0);
uv_write_t req;
uv_buf_t buf;
buf.base = (char*) "Hello TTY\n";
buf.len = strlen(buf.base);
uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL);
uv_tty_reset_mode();
#endif
return uv_run(loop, UV_RUN_DEFAULT);
}
@santigimeno
Copy link

Accidentally I came across this issue. In case you didn't find out what the problem was, the issue is with the local variables defined in the ttyThing function. As they're allocated in the stack, as soon as the function exists they cease to exist. Declaring:

uv_tty_t tty;
uv_write_t req;
uv_buf_t buf;

globally fixes the issue.

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