Merge pull request #761 'fix a few strncpy calls by using xstrlcpy'

This commit is contained in:
Thiago de Arruda 2014-05-26 13:09:42 -03:00
commit fc7bc0412e
5 changed files with 37 additions and 6 deletions

View File

@ -67,7 +67,7 @@ bool try_end(Error *err)
ET_ERROR,
NULL,
&should_free);
strncpy(err->msg, msg, sizeof(err->msg));
xstrlcpy(err->msg, msg, sizeof(err->msg));
err->set = true;
free_global_msglist();

View File

@ -5,10 +5,11 @@
#include "nvim/api/private/defs.h"
#include "nvim/vim.h"
#include "nvim/memory.h"
#define set_api_error(message, err) \
do { \
strncpy(err->msg, message, sizeof(err->msg)); \
xstrlcpy(err->msg, message, sizeof(err->msg)); \
err->set = true; \
} while (0)

View File

@ -183,6 +183,19 @@ char *xstpncpy(char *restrict dst, const char *restrict src, size_t maxlen)
}
}
size_t xstrlcpy(char *restrict dst, const char *restrict src, size_t size)
{
size_t ret = strlen(src);
if (size) {
size_t len = (ret >= size) ? size - 1 : ret;
memcpy(dst, src, len);
dst[len] = '\0';
}
return ret;
}
char *xstrdup(const char *str)
{
char *ret = strdup(str);

View File

@ -125,6 +125,19 @@ char *xstpcpy(char *restrict dst, const char *restrict src);
/// @param maxlen
char *xstpncpy(char *restrict dst, const char *restrict src, size_t maxlen);
/// xstrlcpy - Copy a %NUL terminated string into a sized buffer
///
/// Compatible with *BSD strlcpy: the result is always a valid
/// NUL-terminated string that fits in the buffer (unless,
/// of course, the buffer size is zero). It does not pad
/// out the result like strncpy() does.
///
/// @param dst Where to copy the string to
/// @param src Where to copy the string from
/// @param size Size of destination buffer
/// @return Length of the source string (i.e.: strlen(src))
size_t xstrlcpy(char *restrict dst, const char *restrict src, size_t size);
/// Duplicates a chunk of memory using xmalloc
///
/// @see {xmalloc}

View File

@ -85,7 +85,11 @@ void server_start(char *endpoint, ChannelProtocol prot)
char addr[ADDRESS_MAX_SIZE];
// Trim to `ADDRESS_MAX_SIZE`
strncpy(addr, endpoint, sizeof(addr));
if (xstrlcpy(addr, endpoint, sizeof(addr)) >= sizeof(addr)) {
// TODO(aktau): since this is not what the user wanted, perhaps we
// should return an error here
EMSG2("Address was too long, truncated to %s", addr);
}
// Check if the server already exists
if (map_has(cstr_t)(servers, addr)) {
@ -111,7 +115,7 @@ void server_start(char *endpoint, ChannelProtocol prot)
}
// Extract the address part
strncpy(ip, addr, addr_len);
xstrlcpy(ip, addr, addr_len);
int port = NEOVIM_DEFAULT_TCP_PORT;
@ -183,7 +187,7 @@ void server_stop(char *endpoint)
char addr[ADDRESS_MAX_SIZE];
// Trim to `ADDRESS_MAX_SIZE`
strncpy(addr, endpoint, sizeof(addr));
xstrlcpy(addr, endpoint, sizeof(addr));
if ((server = map_get(cstr_t)(servers, addr)) == NULL) {
EMSG2("Not listening on %s", addr);