gethostname.c: change to report ENAMETOOLONG error when buflen is less
change to behaviour the same as glibc for the check about buflen
Change-Id: I98265a8fe441df6fed2527686f89b087364ca53d
Signed-off-by: Yongqin Liu <yongqin.liu@linaro.org>
diff --git a/libc/Android.mk b/libc/Android.mk
index 893738a..345a1f3 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -43,7 +43,6 @@
bionic/ether_aton.c \
bionic/ether_ntoa.c \
bionic/fts.c \
- bionic/gethostname.c \
bionic/getpriority.c \
bionic/if_indextoname.c \
bionic/if_nametoindex.c \
@@ -120,6 +119,7 @@
bionic/getauxval.cpp \
bionic/getcwd.cpp \
bionic/getentropy_linux.c \
+ bionic/gethostname.cpp \
bionic/getpgrp.cpp \
bionic/getpid.cpp \
bionic/gettid.cpp \
diff --git a/libc/bionic/gethostname.c b/libc/bionic/gethostname.cpp
similarity index 78%
rename from libc/bionic/gethostname.c
rename to libc/bionic/gethostname.cpp
index 5d3d7d9..962fea1 100644
--- a/libc/bionic/gethostname.c
+++ b/libc/bionic/gethostname.cpp
@@ -25,27 +25,24 @@
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
+
#include <errno.h>
-#include <unistd.h>
#include <string.h>
#include <sys/utsname.h>
+#include <unistd.h>
-int gethostname(char* buff, size_t buflen)
-{
- struct utsname name;
- int result = 0;
+int gethostname(char* buf, size_t n) {
+ struct utsname name;
+ if (uname(&name) == -1) {
+ return -1;
+ }
- result = uname(&name);
- if (result != -1)
- {
- int namelen = strlen(name.nodename);
+ size_t name_length = static_cast<size_t>(strlen(name.nodename) + 1);
+ if (name_length > n) {
+ errno = ENAMETOOLONG;
+ return -1;
+ }
- if ((int)buflen < namelen+1) {
- errno = EINVAL;
- result = -1;
- } else {
- memcpy( buff, name.nodename, namelen+1 );
- }
- }
- return result;
+ memcpy(buf, name.nodename, name_length);
+ return 0;
}