[libc++] Avoid UB in the no-exceptions mode in a few places

Summary:
A few places in the library seem to behave unexpectedly when the library
is compiled or used with exceptions disabled. For example, not throwing
an exception when a pointer is NULL can lead us to dereference the pointer
later on, which is UB. This patch fixes such occurences.

It's hard to tell whether there are other places where the no-exceptions
mode misbehaves like this, because the replacement for throwing an
exception does not always seem to be abort()ing, but at least this
patch will improve the situation somewhat.

See http://lists.llvm.org/pipermail/libcxx-dev/2019-January/000172.html

Reviewers: mclow.lists, EricWF

Subscribers: christof, jkorous, dexonsmith, libcxx-commits

Differential Revision: https://reviews.llvm.org/D57761

git-svn-id: https://llvm.org/svn/llvm-project/libcxx/trunk@353850 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/include/ios b/include/ios
index 9633639..96e84eb 100644
--- a/include/ios
+++ b/include/ios
@@ -425,6 +425,16 @@
     virtual ~failure() throw();
 };
 
+_LIBCPP_NORETURN inline _LIBCPP_INLINE_VISIBILITY
+void __throw_failure(char const* __msg) {
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    throw ios_base::failure(__msg);
+#else
+    ((void)__msg);
+    _VSTD::abort();
+#endif
+}
+
 class _LIBCPP_TYPE_VIS ios_base::Init
 {
 public:
diff --git a/include/map b/include/map
index 47f5c67..e21dd5a 100644
--- a/include/map
+++ b/include/map
@@ -1535,10 +1535,8 @@
 {
     __parent_pointer __parent;
     __node_base_pointer& __child = __tree_.__find_equal(__parent, __k);
-#ifndef _LIBCPP_NO_EXCEPTIONS
     if (__child == nullptr)
-        throw out_of_range("map::at:  key not found");
-#endif  // _LIBCPP_NO_EXCEPTIONS
+        __throw_out_of_range("map::at:  key not found");
     return static_cast<__node_pointer>(__child)->__value_.__get_value().second;
 }
 
@@ -1548,10 +1546,8 @@
 {
     __parent_pointer __parent;
     __node_base_pointer __child = __tree_.__find_equal(__parent, __k);
-#ifndef _LIBCPP_NO_EXCEPTIONS
     if (__child == nullptr)
-        throw out_of_range("map::at:  key not found");
-#endif  // _LIBCPP_NO_EXCEPTIONS
+        __throw_out_of_range("map::at:  key not found");
     return static_cast<__node_pointer>(__child)->__value_.__get_value().second;
 }
 
diff --git a/include/unordered_map b/include/unordered_map
index 87278b0..7ae9805 100644
--- a/include/unordered_map
+++ b/include/unordered_map
@@ -1602,10 +1602,8 @@
 unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::at(const key_type& __k)
 {
     iterator __i = find(__k);
-#ifndef _LIBCPP_NO_EXCEPTIONS
     if (__i == end())
-        throw out_of_range("unordered_map::at: key not found");
-#endif  // _LIBCPP_NO_EXCEPTIONS
+        __throw_out_of_range("unordered_map::at: key not found");
     return __i->second;
 }
 
@@ -1614,10 +1612,8 @@
 unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::at(const key_type& __k) const
 {
     const_iterator __i = find(__k);
-#ifndef _LIBCPP_NO_EXCEPTIONS
     if (__i == end())
-        throw out_of_range("unordered_map::at: key not found");
-#endif  // _LIBCPP_NO_EXCEPTIONS
+        __throw_out_of_range("unordered_map::at: key not found");
     return __i->second;
 }
 
diff --git a/src/hash.cpp b/src/hash.cpp
index 1631b91..89bb736 100644
--- a/src/hash.cpp
+++ b/src/hash.cpp
@@ -153,12 +153,8 @@
 typename enable_if<_Sz == 4, void>::type
 __check_for_overflow(size_t N)
 {
-#ifndef _LIBCPP_NO_EXCEPTIONS
     if (N > 0xFFFFFFFB)
-        throw overflow_error("__next_prime overflow");
-#else
-    (void)N;
-#endif
+        __throw_overflow_error("__next_prime overflow");
 }
 
 template <size_t _Sz = sizeof(size_t)>
@@ -166,12 +162,8 @@
 typename enable_if<_Sz == 8, void>::type
 __check_for_overflow(size_t N)
 {
-#ifndef _LIBCPP_NO_EXCEPTIONS
     if (N > 0xFFFFFFFFFFFFFFC5ull)
-        throw overflow_error("__next_prime overflow");
-#else
-    (void)N;
-#endif
+        __throw_overflow_error("__next_prime overflow");
 }
 
 size_t
diff --git a/src/ios.cpp b/src/ios.cpp
index fdff2e8..2dc84be 100644
--- a/src/ios.cpp
+++ b/src/ios.cpp
@@ -266,10 +266,9 @@
         __rdstate_ = state;
     else
         __rdstate_ = state | badbit;
-#ifndef _LIBCPP_NO_EXCEPTIONS
+
     if (((state | (__rdbuf_ ? goodbit : badbit)) & __exceptions_) != 0)
-        throw failure("ios_base::clear");
-#endif  // _LIBCPP_NO_EXCEPTIONS
+        __throw_failure("ios_base::clear");
 }
 
 // init
@@ -309,35 +308,27 @@
     {
         size_t newesize = sizeof(event_callback) * rhs.__event_size_;
         new_callbacks.reset(static_cast<event_callback*>(malloc(newesize)));
-#ifndef _LIBCPP_NO_EXCEPTIONS
         if (!new_callbacks)
-            throw bad_alloc();
-#endif  // _LIBCPP_NO_EXCEPTIONS
+            __throw_bad_alloc();
 
         size_t newisize = sizeof(int) * rhs.__event_size_;
         new_ints.reset(static_cast<int *>(malloc(newisize)));
-#ifndef _LIBCPP_NO_EXCEPTIONS
         if (!new_ints)
-            throw bad_alloc();
-#endif  // _LIBCPP_NO_EXCEPTIONS
+            __throw_bad_alloc();
     }
     if (__iarray_cap_ < rhs.__iarray_size_)
     {
         size_t newsize = sizeof(long) * rhs.__iarray_size_;
         new_longs.reset(static_cast<long*>(malloc(newsize)));
-#ifndef _LIBCPP_NO_EXCEPTIONS
         if (!new_longs)
-            throw bad_alloc();
-#endif  // _LIBCPP_NO_EXCEPTIONS
+            __throw_bad_alloc();
     }
     if (__parray_cap_ < rhs.__parray_size_)
     {
         size_t newsize = sizeof(void*) * rhs.__parray_size_;
         new_pointers.reset(static_cast<void**>(malloc(newsize)));
-#ifndef _LIBCPP_NO_EXCEPTIONS
         if (!new_pointers)
-            throw bad_alloc();
-#endif  // _LIBCPP_NO_EXCEPTIONS
+            __throw_bad_alloc();
     }
     // Got everything we need.  Copy everything but __rdstate_, __rdbuf_ and __exceptions_
     __fmtflags_ = rhs.__fmtflags_;
diff --git a/src/locale.cpp b/src/locale.cpp
index 18edad7..00eb574 100644
--- a/src/locale.cpp
+++ b/src/locale.cpp
@@ -468,10 +468,8 @@
 const locale::facet*
 locale::__imp::use_facet(long id) const
 {
-#ifndef _LIBCPP_NO_EXCEPTIONS
     if (!has_facet(id))
-        throw bad_cast();
-#endif  // _LIBCPP_NO_EXCEPTIONS
+        __throw_bad_cast();
     return facets_[static_cast<size_t>(id)];
 }
 
@@ -537,12 +535,8 @@
 }
 
 locale::locale(const char* name)
-#ifndef _LIBCPP_NO_EXCEPTIONS
     : __locale_(name ? new __imp(name)
-                     : throw runtime_error("locale constructed with null"))
-#else  // _LIBCPP_NO_EXCEPTIONS
-    : __locale_(new __imp(name))
-#endif
+                     : (__throw_runtime_error("locale constructed with null"), (__imp*)0))
 {
     __locale_->__add_shared();
 }
@@ -554,12 +548,8 @@
 }
 
 locale::locale(const locale& other, const char* name, category c)
-#ifndef _LIBCPP_NO_EXCEPTIONS
     : __locale_(name ? new __imp(*other.__locale_, name, c)
-                     : throw runtime_error("locale constructed with null"))
-#else  // _LIBCPP_NO_EXCEPTIONS
-    : __locale_(new __imp(*other.__locale_, name, c))
-#endif
+                     : (__throw_runtime_error("locale constructed with null"), (__imp*)0))
 {
     __locale_->__add_shared();
 }
diff --git a/test/libcxx/containers/associative/map/at.abort.pass.cpp b/test/libcxx/containers/associative/map/at.abort.pass.cpp
new file mode 100644
index 0000000..d34f48f
--- /dev/null
+++ b/test/libcxx/containers/associative/map/at.abort.pass.cpp
@@ -0,0 +1,34 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <map>
+
+// class map
+
+// mapped_type& at(const key_type& k);
+
+// Make sure we abort() when exceptions are disabled and we fetch a key that
+// is not in the map.
+
+// REQUIRES: libcpp-no-exceptions
+
+#include <csignal>
+#include <cstdlib>
+#include <map>
+
+
+void exit_success(int) {
+    std::_Exit(EXIT_SUCCESS);
+}
+
+int main(int, char**) {
+    std::signal(SIGABRT, exit_success);
+    std::map<int, int> map;
+    map.at(1);
+    return EXIT_FAILURE;
+}
diff --git a/test/libcxx/containers/associative/map/at.const.abort.pass.cpp b/test/libcxx/containers/associative/map/at.const.abort.pass.cpp
new file mode 100644
index 0000000..705ada8
--- /dev/null
+++ b/test/libcxx/containers/associative/map/at.const.abort.pass.cpp
@@ -0,0 +1,34 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <map>
+
+// class map
+
+// const mapped_type& at(const key_type& k) const;
+
+// Make sure we abort() when exceptions are disabled and we fetch a key that
+// is not in the map.
+
+// REQUIRES: libcpp-no-exceptions
+
+#include <csignal>
+#include <cstdlib>
+#include <map>
+
+
+void exit_success(int) {
+    std::_Exit(EXIT_SUCCESS);
+}
+
+int main(int, char**) {
+    std::signal(SIGABRT, exit_success);
+    std::map<int, int> const map;
+    map.at(1);
+    return EXIT_FAILURE;
+}
diff --git a/test/libcxx/containers/unord/unord.map/at.abort.pass.cpp b/test/libcxx/containers/unord/unord.map/at.abort.pass.cpp
new file mode 100644
index 0000000..b65af16
--- /dev/null
+++ b/test/libcxx/containers/unord/unord.map/at.abort.pass.cpp
@@ -0,0 +1,31 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <unordered_map>
+
+// class unordered_map
+
+// mapped_type& at(const key_type& k);
+
+// Make sure we abort() when exceptions are disabled and we fetch a key that
+// is not in the map.
+
+// REQUIRES: libcpp-no-exceptions
+// UNSUPPORTED: c++98, c++03
+
+#include <csignal>
+#include <cstdlib>
+#include <unordered_map>
+
+
+int main(int, char**) {
+    std::signal(SIGABRT, [](int) { std::_Exit(EXIT_SUCCESS); });
+    std::unordered_map<int, int> map;
+    map.at(1);
+    return EXIT_FAILURE;
+}
diff --git a/test/libcxx/containers/unord/unord.map/at.const.abort.pass.cpp b/test/libcxx/containers/unord/unord.map/at.const.abort.pass.cpp
new file mode 100644
index 0000000..af2a2cd
--- /dev/null
+++ b/test/libcxx/containers/unord/unord.map/at.const.abort.pass.cpp
@@ -0,0 +1,31 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <unordered_map>
+
+// class unordered_map
+
+// const mapped_type& at(const key_type& k) const;
+
+// Make sure we abort() when exceptions are disabled and we fetch a key that
+// is not in the map.
+
+// REQUIRES: libcpp-no-exceptions
+// UNSUPPORTED: c++98, c++03
+
+#include <csignal>
+#include <cstdlib>
+#include <unordered_map>
+
+
+int main(int, char**) {
+    std::signal(SIGABRT, [](int) { std::_Exit(EXIT_SUCCESS); });
+    std::unordered_map<int, int> const map;
+    map.at(1);
+    return EXIT_FAILURE;
+}
diff --git a/test/libcxx/input.output/iostreams.base/ios/iostate.flags/clear.abort.pass.cpp b/test/libcxx/input.output/iostreams.base/ios/iostate.flags/clear.abort.pass.cpp
new file mode 100644
index 0000000..e6dc1c9
--- /dev/null
+++ b/test/libcxx/input.output/iostreams.base/ios/iostate.flags/clear.abort.pass.cpp
@@ -0,0 +1,41 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <ios>
+
+// template <class charT, class traits> class basic_ios
+
+// void clear(iostate state);
+
+// Make sure that we abort() when exceptions are disabled and the exception
+// flag is set for the iostate we pass to clear().
+
+// REQUIRES: libcpp-no-exceptions
+
+#include <csignal>
+#include <cstdlib>
+#include <ios>
+#include <streambuf>
+
+
+void exit_success(int) {
+    std::_Exit(EXIT_SUCCESS);
+}
+
+struct testbuf : public std::streambuf {};
+
+int main(int, char**) {
+    std::signal(SIGABRT, exit_success);
+
+    testbuf buf;
+    std::ios ios(&buf);
+    ios.exceptions(std::ios::badbit);
+    ios.clear(std::ios::badbit);
+
+    return EXIT_FAILURE;
+}
diff --git a/test/libcxx/localization/locales/locale.abort.pass.cpp b/test/libcxx/localization/locales/locale.abort.pass.cpp
new file mode 100644
index 0000000..5817ebd
--- /dev/null
+++ b/test/libcxx/localization/locales/locale.abort.pass.cpp
@@ -0,0 +1,34 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <locale>
+
+// class locale;
+
+// explicit locale( const char* std_name );
+
+// REQUIRES: libcpp-no-exceptions
+
+// Make sure we abort() when we construct a locale with a null name and
+// exceptions are disabled.
+
+#include <csignal>
+#include <cstdlib>
+#include <locale>
+
+
+void exit_success(int) {
+    std::_Exit(EXIT_SUCCESS);
+}
+
+int main(int, char**) {
+    std::signal(SIGABRT, exit_success);
+    std::locale loc(NULL);
+    (void)loc;
+    return EXIT_FAILURE;
+}
diff --git a/test/libcxx/localization/locales/locale.category.abort.pass.cpp b/test/libcxx/localization/locales/locale.category.abort.pass.cpp
new file mode 100644
index 0000000..cf50415
--- /dev/null
+++ b/test/libcxx/localization/locales/locale.category.abort.pass.cpp
@@ -0,0 +1,34 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <locale>
+
+// class locale;
+
+// locale(const locale& other, const char* std_name, category cat);
+
+// REQUIRES: libcpp-no-exceptions
+
+// Make sure we abort() when we construct a locale with a null name and
+// exceptions are disabled.
+
+#include <csignal>
+#include <cstdlib>
+#include <locale>
+
+
+void exit_success(int) {
+    std::_Exit(EXIT_SUCCESS);
+}
+
+int main(int, char**) {
+    std::signal(SIGABRT, exit_success);
+    std::locale loc(std::locale(), NULL, std::locale::ctype);
+    (void)loc;
+    return EXIT_FAILURE;
+}
diff --git a/test/libcxx/localization/locales/use_facet.abort.pass.cpp b/test/libcxx/localization/locales/use_facet.abort.pass.cpp
new file mode 100644
index 0000000..64700ea
--- /dev/null
+++ b/test/libcxx/localization/locales/use_facet.abort.pass.cpp
@@ -0,0 +1,37 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <locale>
+
+// template <class Facet> const Facet& use_facet(const locale& loc);
+
+// REQUIRES: libcpp-no-exceptions
+
+// Make sure we abort() when we pass a facet not associated to the locale to
+// use_facet() and exceptions are disabled.
+
+#include <csignal>
+#include <cstdlib>
+#include <locale>
+
+
+struct my_facet : public std::locale::facet {
+    static std::locale::id id;
+};
+
+std::locale::id my_facet::id;
+
+void exit_success(int) {
+    std::_Exit(EXIT_SUCCESS);
+}
+
+int main(int, char**) {
+    std::signal(SIGABRT, exit_success);
+    std::use_facet<my_facet>(std::locale());
+    return EXIT_FAILURE;
+}