{"thread":{"id":"57207","subject":"[PATCH 0/1] Async-signal safety in signal handlers","startedAt":"2022-01-07T10:54:08Z","lastAt":"2022-01-11T02:11:24Z","messageCount":6,"participants":["Patrick Steinhardt","brian m. carlson","Taylor Blau","Phillip Wood"],"isPatch":true,"patchVersion":1,"patchTotal":1},"messages":[{"id":"445695","messageId":"cover.1641552500.git.ps@pks.im","threadId":"57207","inReplyTo":null,"subject":"[PATCH 0/1] Async-signal safety in signal handlers","fromName":"Patrick Steinhardt","fromEmail":"ps@pks.im","sentAt":"2022-01-07T10:53:35Z","receivedAt":"2022-01-07T10:54:08Z","isPatch":true,"sender":{"key":"ps@pks.im","avatar":"https://avatars.githubusercontent.com/u/4056630?v=4"},"body":"Hi,\n\nwe have recently observed a Git process which has been hanging around\nfor more than a month on one of our servers in production. A backtrace\nshowed that the git-fetch(1) process was deadlocked in its signal\nhandler while trying to free memory. Functions like malloc, free and\nmost I/O functions aren't reentrant though, which means they must not be\nexecuted in async signal handlers as specified in signal-safety(7).\n\nThe fix for git-fetch(1) is rather simple: we can just unlink(2) the\nlockfiles, which is indeed allowed, but skip free'ing memory. But in\nfact, this is a wider issue we have: we mostly didn't pay attention to\nthose restrictions, and thus we freely call non-async-signal-safe\nfunctions. It's less clear what to do about this in most of the cases\nthough:\n\n- git-clone(1) tries to clean up the \".git\" directory and its worktree\n  on being killed, but needs to allocate memory to compute corresponding\n  paths. We can try to preallocate the buffer, but it's not clear\n  whether there is a proper upper boundary.\n\n- git-gc(1) will try to commit \"gc.log\" and write to stderr, both of\n  which aren't allowed. I think we'll have to just bail and leave it\n  behind in a partially-written state.\n\n- git-repack(1) tries to remove \"pack/.tmp-*\" files, calling opendir(3P),\n  readdir(3P), closedir(3P) and allocates memory. We probably have to\n  keep track of all temporary files we create in a global list, which we\n  can then access in our signal handler.\n\n- git-worktree(1) is doing the same as git-clone(1), trying to prune the\n  new worktree if it's killed. Again, we'd probably have to preallocate\n  a buffer to compute paths.\n\n- HTTP pushes do all sorts of HTTP requests in their signal handler to\n  unlock the remote server. I don't really see what to do about this\n  except drop the code -- setting a global \"please clean up and exit\n  now\" flags is probably not going to fly well.\n\nThe tempfiles and tmp-objdir code already handles signals correctly.\n\nPatrick\n\nPatrick Steinhardt (1):\n  fetch: fix deadlock when cleaning up lockfiles in async signals\n\n builtin/clone.c |  2 +-\n builtin/fetch.c | 17 +++++++++++------\n transport.c     | 11 ++++++++---\n transport.h     | 14 +++++++++++++-\n 4 files changed, 33 insertions(+), 11 deletions(-)\n\n-- \n2.34.1\n\n"},{"id":"445697","messageId":"555ec6717ecab0fe6ef5660bcf0d61d59f84ef8b.1641552500.git.ps@pks.im","threadId":"57207","inReplyTo":"cover.1641552500.git.ps@pks.im","subject":"[PATCH 1/1] fetch: fix deadlock when cleaning up lockfiles in async signals","fromName":"Patrick Steinhardt","fromEmail":"ps@pks.im","sentAt":"2022-01-07T10:55:47Z","receivedAt":"2022-01-07T10:56:14Z","isPatch":true,"sender":{"key":"ps@pks.im","avatar":"https://avatars.githubusercontent.com/u/4056630?v=4"},"body":"[Resend with the correct In-Reply-To header set to fix threading]\n\nWhen fetching packfiles, we write a bunch of lockfiles for the packfiles\nwe're writing into the repository. In order to not leave behind any\ncruft in case we exit or receive a signal, we register both an exit\nhandler as well as signal handlers for common signals like SIGINT. These\nhandlers will then unlink the locks and free the data structure tracking\nthem. We have observed a deadlock in this logic though:\n\n    (gdb) bt\n    #0  __lll_lock_wait_private () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:95\n    #1  0x00007f4932bea2cd in _int_free (av=0x7f4932f2eb20 <main_arena>, p=0x3e3e4200, have_lock=0) at malloc.c:3969\n    #2  0x00007f4932bee58c in __GI___libc_free (mem=<optimized out>) at malloc.c:2975\n    #3  0x0000000000662ab1 in string_list_clear ()\n    #4  0x000000000044f5bc in unlock_pack_on_signal ()\n    #5  <signal handler called>\n    #6  _int_free (av=0x7f4932f2eb20 <main_arena>, p=<optimized out>, have_lock=0) at malloc.c:4024\n    #7  0x00007f4932bee58c in __GI___libc_free (mem=<optimized out>) at malloc.c:2975\n    #8  0x000000000065afd5 in strbuf_release ()\n    #9  0x000000000066ddb9 in delete_tempfile ()\n    #10 0x0000000000610d0b in files_transaction_cleanup.isra ()\n    #11 0x0000000000611718 in files_transaction_abort ()\n    #12 0x000000000060d2ef in ref_transaction_abort ()\n    #13 0x000000000060d441 in ref_transaction_prepare ()\n    #14 0x000000000060e0b5 in ref_transaction_commit ()\n    #15 0x00000000004511c2 in fetch_and_consume_refs ()\n    #16 0x000000000045279a in cmd_fetch ()\n    #17 0x0000000000407c48 in handle_builtin ()\n    #18 0x0000000000408df2 in cmd_main ()\n    #19 0x00000000004078b5 in main ()\n\nThe process was killed with a signal, which caused the signal handler to\nkick in and try free the data structures after we have unlinked the\nlocks. It then deadlocks while calling free(3P).\n\nThe root cause of this is that it is not allowed to call certain\nfunctions in async-signal handlers, as specified by signal-safety(7).\nNext to most I/O functions, this list of disallowed functions also\nincludes memory-handling functions like malloc(3P) and free(3P) because\nthey may not be reentrant. As a result, if we execute such functions in\nthe signal handler, then they may operate on inconistent state and fail\nin unexpected ways.\n\nFix this bug by not calling non-async-signal-safe functions when running\nin the signal handler. We're about to re-raise the signal anyway and\nwill thus exit, so it's not much of a problem to keep the string list of\nlockfiles untouched. Note that it's fine though to call unlink(2), so\nwe'll still clean up the lockfiles correctly.\n\nSigned-off-by: Patrick Steinhardt <ps@pks.im>\n---\n builtin/clone.c |  2 +-\n builtin/fetch.c | 17 +++++++++++------\n transport.c     | 11 ++++++++---\n transport.h     | 14 +++++++++++++-\n 4 files changed, 33 insertions(+), 11 deletions(-)\n\ndiff --git a/builtin/clone.c b/builtin/clone.c\nindex 5bed37f8b5..585eef9b9a 100644\n--- a/builtin/clone.c\n+++ b/builtin/clone.c\n@@ -1290,7 +1290,7 @@ int cmd_clone(int argc, const char **argv, const char *prefix)\n \t */\n \tsubmodule_progress = transport->progress;\n \n-\ttransport_unlock_pack(transport);\n+\ttransport_unlock_pack(transport, 0);\n \ttransport_disconnect(transport);\n \n \tif (option_dissociate) {\ndiff --git a/builtin/fetch.c b/builtin/fetch.c\nindex f1fe73a3e0..4bc04522ed 100644\n--- a/builtin/fetch.c\n+++ b/builtin/fetch.c\n@@ -223,17 +223,22 @@ static struct option builtin_fetch_options[] = {\n \tOPT_END()\n };\n \n-static void unlock_pack(void)\n+static void unlock_pack(unsigned int flags)\n {\n \tif (gtransport)\n-\t\ttransport_unlock_pack(gtransport);\n+\t\ttransport_unlock_pack(gtransport, flags);\n \tif (gsecondary)\n-\t\ttransport_unlock_pack(gsecondary);\n+\t\ttransport_unlock_pack(gsecondary, flags);\n+}\n+\n+static void unlock_pack_atexit(void)\n+{\n+\tunlock_pack(0);\n }\n \n static void unlock_pack_on_signal(int signo)\n {\n-\tunlock_pack();\n+\tunlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);\n \tsigchain_pop(signo);\n \traise(signo);\n }\n@@ -1329,7 +1334,7 @@ static int fetch_and_consume_refs(struct transport *transport,\n \ttrace2_region_leave(\"fetch\", \"consume_refs\", the_repository);\n \n out:\n-\ttransport_unlock_pack(transport);\n+\ttransport_unlock_pack(transport, 0);\n \treturn ret;\n }\n \n@@ -1978,7 +1983,7 @@ static int fetch_one(struct remote *remote, int argc, const char **argv,\n \t\tgtransport->server_options = &server_options;\n \n \tsigchain_push_common(unlock_pack_on_signal);\n-\tatexit(unlock_pack);\n+\tatexit(unlock_pack_atexit);\n \tsigchain_push(SIGPIPE, SIG_IGN);\n \texit_code = do_fetch(gtransport, &rs);\n \tsigchain_pop(SIGPIPE);\ndiff --git a/transport.c b/transport.c\nindex 92ab9a3fa6..2a3e324154 100644\n--- a/transport.c\n+++ b/transport.c\n@@ -1456,13 +1456,18 @@ int transport_fetch_refs(struct transport *transport, struct ref *refs)\n \treturn rc;\n }\n \n-void transport_unlock_pack(struct transport *transport)\n+void transport_unlock_pack(struct transport *transport, unsigned int flags)\n {\n+\tint in_signal_handler = !!(flags & TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);\n \tint i;\n \n \tfor (i = 0; i < transport->pack_lockfiles.nr; i++)\n-\t\tunlink_or_warn(transport->pack_lockfiles.items[i].string);\n-\tstring_list_clear(&transport->pack_lockfiles, 0);\n+\t\tif (in_signal_handler)\n+\t\t\tunlink(transport->pack_lockfiles.items[i].string);\n+\t\telse\n+\t\t\tunlink_or_warn(transport->pack_lockfiles.items[i].string);\n+\tif (!in_signal_handler)\n+\t\tstring_list_clear(&transport->pack_lockfiles, 0);\n }\n \n int transport_connect(struct transport *transport, const char *name,\ndiff --git a/transport.h b/transport.h\nindex 8bb4c8bbc8..3f16e50c19 100644\n--- a/transport.h\n+++ b/transport.h\n@@ -279,7 +279,19 @@ const struct ref *transport_get_remote_refs(struct transport *transport,\n  */\n const struct git_hash_algo *transport_get_hash_algo(struct transport *transport);\n int transport_fetch_refs(struct transport *transport, struct ref *refs);\n-void transport_unlock_pack(struct transport *transport);\n+\n+/*\n+ * If this flag is set, unlocking will avoid to call non-async-signal-safe\n+ * functions. This will necessarily leave behind some data structures which\n+ * cannot be cleaned up.\n+ */\n+#define TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER (1 << 0)\n+\n+/*\n+ * Unlock all packfiles locked by the transport.\n+ */\n+void transport_unlock_pack(struct transport *transport, unsigned int flags);\n+\n int transport_disconnect(struct transport *transport);\n char *transport_anonymize_url(const char *url);\n void transport_take_over(struct transport *transport,\n-- \n2.34.1\n\n"},{"id":"445698","messageId":"YdggneOlWXf2Z+gf@camp.crustytoothpaste.net","threadId":"57207","inReplyTo":"555ec6717ecab0fe6ef5660bcf0d61d59f84ef8b.1641552500.git.ps@pks.im","subject":"Re: [PATCH 1/1] fetch: fix deadlock when cleaning up lockfiles in async signals","fromName":"brian m. carlson","fromEmail":"sandals@crustytoothpaste.net","sentAt":"2022-01-07T11:14:37Z","receivedAt":"2022-01-07T11:14:41Z","isPatch":true,"sender":{"key":"sandals@crustytoothpaste.net","avatar":"https://avatars.githubusercontent.com/u/497054?v=4"},"body":"On 2022-01-07 at 10:55:47, Patrick Steinhardt wrote:\n> [Resend with the correct In-Reply-To header set to fix threading]\n> \n> When fetching packfiles, we write a bunch of lockfiles for the packfiles\n> we're writing into the repository. In order to not leave behind any\n> cruft in case we exit or receive a signal, we register both an exit\n> handler as well as signal handlers for common signals like SIGINT. These\n> handlers will then unlink the locks and free the data structure tracking\n> them. We have observed a deadlock in this logic though:\n> \n>     (gdb) bt\n>     #0  __lll_lock_wait_private () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:95\n>     #1  0x00007f4932bea2cd in _int_free (av=0x7f4932f2eb20 <main_arena>, p=0x3e3e4200, have_lock=0) at malloc.c:3969\n>     #2  0x00007f4932bee58c in __GI___libc_free (mem=<optimized out>) at malloc.c:2975\n>     #3  0x0000000000662ab1 in string_list_clear ()\n>     #4  0x000000000044f5bc in unlock_pack_on_signal ()\n>     #5  <signal handler called>\n>     #6  _int_free (av=0x7f4932f2eb20 <main_arena>, p=<optimized out>, have_lock=0) at malloc.c:4024\n>     #7  0x00007f4932bee58c in __GI___libc_free (mem=<optimized out>) at malloc.c:2975\n>     #8  0x000000000065afd5 in strbuf_release ()\n>     #9  0x000000000066ddb9 in delete_tempfile ()\n>     #10 0x0000000000610d0b in files_transaction_cleanup.isra ()\n>     #11 0x0000000000611718 in files_transaction_abort ()\n>     #12 0x000000000060d2ef in ref_transaction_abort ()\n>     #13 0x000000000060d441 in ref_transaction_prepare ()\n>     #14 0x000000000060e0b5 in ref_transaction_commit ()\n>     #15 0x00000000004511c2 in fetch_and_consume_refs ()\n>     #16 0x000000000045279a in cmd_fetch ()\n>     #17 0x0000000000407c48 in handle_builtin ()\n>     #18 0x0000000000408df2 in cmd_main ()\n>     #19 0x00000000004078b5 in main ()\n> \n> The process was killed with a signal, which caused the signal handler to\n> kick in and try free the data structures after we have unlinked the\n> locks. It then deadlocks while calling free(3P).\n> \n> The root cause of this is that it is not allowed to call certain\n> functions in async-signal handlers, as specified by signal-safety(7).\n> Next to most I/O functions, this list of disallowed functions also\n> includes memory-handling functions like malloc(3P) and free(3P) because\n> they may not be reentrant. As a result, if we execute such functions in\n> the signal handler, then they may operate on inconistent state and fail\n> in unexpected ways.\n> \n> Fix this bug by not calling non-async-signal-safe functions when running\n> in the signal handler. We're about to re-raise the signal anyway and\n> will thus exit, so it's not much of a problem to keep the string list of\n> lockfiles untouched. Note that it's fine though to call unlink(2), so\n> we'll still clean up the lockfiles correctly.\n\nI took a look, and this seems reasonable to me.  I know in the\nnon-signal case, we'd want to clean up because it means we can check for\nleaks, but I don't see the utility of running Git under Valgrind and\nthen sending it a signal, and I think it's just safe to ignore that\ncase.\n-- \nbrian m. carlson (he/him or they/them)\nToronto, Ontario, CA\n"},{"id":"445759","messageId":"YdjBkZsnYd+zYne1@nand.local","threadId":"57207","inReplyTo":"555ec6717ecab0fe6ef5660bcf0d61d59f84ef8b.1641552500.git.ps@pks.im","subject":"Re: [PATCH 1/1] fetch: fix deadlock when cleaning up lockfiles in async signals","fromName":"Taylor Blau","fromEmail":"me@ttaylorr.com","sentAt":"2022-01-07T22:41:21Z","receivedAt":"2022-01-07T22:41:25Z","isPatch":true,"sender":{"key":"me@ttaylorr.com","avatar":"https://avatars.githubusercontent.com/u/301000140?v=4"},"body":"On Fri, Jan 07, 2022 at 11:55:47AM +0100, Patrick Steinhardt wrote:\n> diff --git a/transport.c b/transport.c\n> index 92ab9a3fa6..2a3e324154 100644\n> --- a/transport.c\n> +++ b/transport.c\n> @@ -1456,13 +1456,18 @@ int transport_fetch_refs(struct transport *transport, struct ref *refs)\n>  \treturn rc;\n>  }\n>\n> -void transport_unlock_pack(struct transport *transport)\n> +void transport_unlock_pack(struct transport *transport, unsigned int flags)\n>  {\n> +\tint in_signal_handler = !!(flags & TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);\n>  \tint i;\n>\n>  \tfor (i = 0; i < transport->pack_lockfiles.nr; i++)\n> -\t\tunlink_or_warn(transport->pack_lockfiles.items[i].string);\n> -\tstring_list_clear(&transport->pack_lockfiles, 0);\n> +\t\tif (in_signal_handler)\n> +\t\t\tunlink(transport->pack_lockfiles.items[i].string);\n> +\t\telse\n> +\t\t\tunlink_or_warn(transport->pack_lockfiles.items[i].string);\n\nThis puzzled me when I first read it. But unlink_or_warn() isn't\nreentrant because it performs buffered IO on stderr, so if we reached\nthis signal handler while executing another function call modifying\nthose same buffers, the call within the signal handler would have\nundefined behavior.\n\nSo that makes sense: freeing (with string_list_clear() below) and\nperforming buffered IO (with unlink_or_warn() here as just described)\nare certainly off the table.\n\nBut is unlink() safe as-is? I'm not so sure. Reading signal-safety(7),\nit's clearly on the list of functions that are OK to call. But reading\nthe errno section:\n\n    errno\n      Fetching and setting the value of errno is async-signal-safe\n      provided that the signal handler saves errno on entry and restores\n      its value before returning.\n\nWe certainly not doing that, though that's nothing new, and so I wonder\nwhy it doesn't seem to be an issue in practice.\n\nThanks,\nTaylor\n"},{"id":"445790","messageId":"2d8c1619-74ab-62b3-3a30-8e500a16649e@gmail.com","threadId":"57207","inReplyTo":"YdjBkZsnYd+zYne1@nand.local","subject":"Re: [PATCH 1/1] fetch: fix deadlock when cleaning up lockfiles in async signals","fromName":"Phillip Wood","fromEmail":"phillip.wood123@gmail.com","sentAt":"2022-01-08T10:54:35Z","receivedAt":"2022-01-08T10:54:45Z","isPatch":true,"sender":{"key":"phillip.wood@dunelm.org.uk","avatar":null},"body":"Hi Taylor\n\nOn 07/01/2022 22:41, Taylor Blau wrote:\n> On Fri, Jan 07, 2022 at 11:55:47AM +0100, Patrick Steinhardt wrote:\n>> diff --git a/transport.c b/transport.c\n>> index 92ab9a3fa6..2a3e324154 100644\n>> --- a/transport.c\n>> +++ b/transport.c\n>> @@ -1456,13 +1456,18 @@ int transport_fetch_refs(struct transport *transport, struct ref *refs)\n>>   \treturn rc;\n>>   }\n>>\n>> -void transport_unlock_pack(struct transport *transport)\n>> +void transport_unlock_pack(struct transport *transport, unsigned int flags)\n>>   {\n>> +\tint in_signal_handler = !!(flags & TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);\n>>   \tint i;\n>>\n>>   \tfor (i = 0; i < transport->pack_lockfiles.nr; i++)\n>> -\t\tunlink_or_warn(transport->pack_lockfiles.items[i].string);\n>> -\tstring_list_clear(&transport->pack_lockfiles, 0);\n>> +\t\tif (in_signal_handler)\n>> +\t\t\tunlink(transport->pack_lockfiles.items[i].string);\n>> +\t\telse\n>> +\t\t\tunlink_or_warn(transport->pack_lockfiles.items[i].string);\n> \n> This puzzled me when I first read it. But unlink_or_warn() isn't\n> reentrant because it performs buffered IO on stderr, so if we reached\n> this signal handler while executing another function call modifying\n> those same buffers, the call within the signal handler would have\n> undefined behavior.\n> \n> So that makes sense: freeing (with string_list_clear() below) and\n> performing buffered IO (with unlink_or_warn() here as just described)\n> are certainly off the table.\n> \n> But is unlink() safe as-is? I'm not so sure. Reading signal-safety(7),\n> it's clearly on the list of functions that are OK to call. But reading\n> the errno section:\n> \n>      errno\n>        Fetching and setting the value of errno is async-signal-safe\n>        provided that the signal handler saves errno on entry and restores\n>        its value before returning.\n> \n> We certainly not doing that, though that's nothing new, and so I wonder\n> why it doesn't seem to be an issue in practice.\n\nBecause in this case we re-raise the signal and exit it does not matter \nif unlink() clobbers errno. If instead the program were to continue \nafter handling the signal then we would have to save and restore errno \nto avoid interfering with the code that was running when the signal \nhandler was called.\n\nBest Wishes\n\nPhillip\n\n> Thanks,\n> Taylor\n"},{"id":"445890","messageId":"YdznSPJCSUQwVyg8@nand.local","threadId":"57207","inReplyTo":"2d8c1619-74ab-62b3-3a30-8e500a16649e@gmail.com","subject":"Re: [PATCH 1/1] fetch: fix deadlock when cleaning up lockfiles in async signals","fromName":"Taylor Blau","fromEmail":"me@ttaylorr.com","sentAt":"2022-01-11T02:11:20Z","receivedAt":"2022-01-11T02:11:24Z","isPatch":true,"sender":{"key":"me@ttaylorr.com","avatar":"https://avatars.githubusercontent.com/u/301000140?v=4"},"body":"On Sat, Jan 08, 2022 at 10:54:35AM +0000, Phillip Wood wrote:\n> > But is unlink() safe as-is? I'm not so sure. Reading signal-safety(7),\n> > it's clearly on the list of functions that are OK to call. But reading\n> > the errno section:\n> >\n> > (snip)\n> >\n> > We certainly not doing that, though that's nothing new, and so I wonder\n> > why it doesn't seem to be an issue in practice.\n>\n> Because in this case we re-raise the signal and exit it does not matter if\n> unlink() clobbers errno. If instead the program were to continue after\n> handling the signal then we would have to save and restore errno to avoid\n> interfering with the code that was running when the signal handler was\n> called.\n\nThat makes perfect sense to me. Thanks for a clear explanation.\n\nTaylor\n"}]}