[libc-commits] [PATCH] D146981: [libc] Fix longjmp's fake return in x86_64

Mikhail Ramalho via Phabricator via libc-commits libc-commits at lists.llvm.org
Mon Mar 27 09:16:04 PDT 2023


mikhail.ramalho created this revision.
mikhail.ramalho added a reviewer: sivachandra.
Herald added subscribers: libc-commits, ecnelises, tschuett.
Herald added projects: libc-project, All.
mikhail.ramalho requested review of this revision.

This implements the fake return after a successful longjmp(), as
described in the linux man page:

Following  a  successful  longjmp(), execution continues as if setjmp()
had returned for a second time.  This  "fake"  return  can  be  distin-
guished from a true setjmp() call because the "fake" return returns the
value provided in val.  If the programmer mistakenly passes the value 0
in val, the "fake" return will instead return 1.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D146981

Files:
  libc/src/setjmp/x86_64/longjmp.cpp
  libc/test/src/setjmp/setjmp_test.cpp


Index: libc/test/src/setjmp/setjmp_test.cpp
===================================================================
--- libc/test/src/setjmp/setjmp_test.cpp
+++ libc/test/src/setjmp/setjmp_test.cpp
@@ -28,3 +28,13 @@
   }
   ASSERT_EQ(n, MAX_LOOP + 1);
 }
+
+TEST(LlvmLibcSetJmpTest, SetAndJumpBackValOne) {
+  jmp_buf env;
+
+  int val = __llvm_libc::setjmp(env);
+  if (val == 0)
+    __llvm_libc::longjmp(env, val);
+
+  ASSERT_EQ(val, 1);
+}
\ No newline at end of file
Index: libc/src/setjmp/x86_64/longjmp.cpp
===================================================================
--- libc/src/setjmp/x86_64/longjmp.cpp
+++ libc/src/setjmp/x86_64/longjmp.cpp
@@ -29,6 +29,7 @@
   // |val| in rax. Note that this has to happen before we restore the registers
   // from values in |buf|. Otherwise, once rsp and rbp are updated, we cannot
   // read |val|.
+  val = val == 0 ? 1 : val;
   LIBC_INLINE_ASM("mov %1, %0\n\t" : "=r"(rax) : "m"(val) :);
   LIBC_INLINE_ASM("mov %1, %0\n\t" : "=r"(rbx) : "m"(buf->rbx) :);
   LIBC_INLINE_ASM("mov %1, %0\n\t" : "=r"(rbp) : "m"(buf->rbp) :);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D146981.508690.patch
Type: text/x-patch
Size: 1082 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libc-commits/attachments/20230327/5d29ece7/attachment.bin>


More information about the libc-commits mailing list