Issue #6697: catch _PyUnicode_AsString() errors in getattr() and setattr()
builtin functions.
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index b4bdf11..5d24000 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -479,6 +479,8 @@
         self.assertRaises(TypeError, getattr, sys, 1, "foo")
         self.assertRaises(TypeError, getattr)
         self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
+        # unicode surrogates are not encodable to the default encoding (utf8)
+        self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
 
     def test_hasattr(self):
         import sys
diff --git a/Objects/object.c b/Objects/object.c
index b0a5471..a332c6c 100644
--- a/Objects/object.c
+++ b/Objects/object.c
@@ -799,8 +799,12 @@
 	}
 	if (tp->tp_getattro != NULL)
 		return (*tp->tp_getattro)(v, name);
-	if (tp->tp_getattr != NULL)
-		return (*tp->tp_getattr)(v, _PyUnicode_AsString(name));
+	if (tp->tp_getattr != NULL) {
+		char *name_str = _PyUnicode_AsString(name);
+		if (name_str == NULL)
+			return NULL;
+		return (*tp->tp_getattr)(v, name_str);
+	}
 	PyErr_Format(PyExc_AttributeError,
 		     "'%.50s' object has no attribute '%U'",
 		     tp->tp_name, name);
@@ -840,7 +844,10 @@
 		return err;
 	}
 	if (tp->tp_setattr != NULL) {
-		err = (*tp->tp_setattr)(v, _PyUnicode_AsString(name), value);
+		char *name_str = _PyUnicode_AsString(name);
+		if (name_str == NULL)
+			return -1;
+		err = (*tp->tp_setattr)(v, name_str, value);
 		Py_DECREF(name);
 		return err;
 	}
@@ -1019,8 +1026,8 @@
 	}
 
 	PyErr_Format(PyExc_AttributeError,
-		     "'%.50s' object has no attribute '%.400s'",
-		     tp->tp_name, _PyUnicode_AsString(name));
+		     "'%.50s' object has no attribute '%U'",
+		     tp->tp_name, name);
   done:
 	Py_DECREF(name);
 	return res;