From mboxrd@z Thu Jan 1 00:00:00 1970
From: Pratyush Yadav
Date: Thu, 6 May 2021 22:37:41 +0530
Subject: [PATCH v2 01/50] lib: Add memdup()
In-Reply-To: <20210506082420.v2.1.I1d417387eb1e7273b536017f4a8920fc4e2369a9@changeid>
References: <20210506142438.1310977-1-sjg@chromium.org>
<20210506082420.v2.1.I1d417387eb1e7273b536017f4a8920fc4e2369a9@changeid>
Message-ID: <20210506170739.4tz7yumpfp2kfli4@ti.com>
List-Id:
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
To: u-boot@lists.denx.de
On 06/05/21 08:23AM, Simon Glass wrote:
> Add a function to duplicate a memory region, a little like strdup().
>
> Signed-off-by: Simon Glass
> ---
>
> Changes in v2:
> - Add a patch to introduce a memdup() function
>
> include/linux/string.h | 13 +++++++++++++
> lib/string.c | 13 +++++++++++++
> test/lib/string.c | 32 ++++++++++++++++++++++++++++++++
> 3 files changed, 58 insertions(+)
>
> diff --git a/include/linux/string.h b/include/linux/string.h
> index dd255f21633..3169c93796e 100644
> --- a/include/linux/string.h
> +++ b/include/linux/string.h
> @@ -129,6 +129,19 @@ extern void * memchr(const void *,int,__kernel_size_t);
> void *memchr_inv(const void *, int, size_t);
> #endif
>
> +/**
> + * memdup() - allocate a buffer and copy in the contents
> + *
> + * Note that this returns a valid pointer even if @len is 0
I'm uneducated about U-Boot's memory allocator. But I wonder how it
returns a valid pointer even on 0 length allocations. What location does
it point to? What are users expected to do with that pointer? They
obviously can't read/write to it since it is supposed to be a 0 byte
long allocation. If another positive length allocation happens before
the said pointer is freed, will it point to the same memory location? If
not, isn't the 0-length pointer actually at least a 1-length pointer?
> + *
> + * @src: data to copy in
> + * @len: number of bytes to copy
> + * @return allocated buffer with the copied contents, or NULL if not enough
> + * memory is available
> + *
> + */
> +char *memdup(const void *src, size_t len);
> +
> unsigned long ustrtoul(const char *cp, char **endp, unsigned int base);
> unsigned long long ustrtoull(const char *cp, char **endp, unsigned int base);
>
> diff --git a/lib/string.c b/lib/string.c
> index a0cff8fe88e..1be61ee0499 100644
> --- a/lib/string.c
> +++ b/lib/string.c
> @@ -658,6 +658,19 @@ void * memscan(void * addr, int c, size_t size)
> }
> #endif
>
> +char *memdup(const void *src, size_t len)
> +{
> + char *p;
> +
> + p = malloc(len);
> + if (!p)
> + return NULL;
> +
> + memcpy(p, src, len);
> +
> + return p;
> +}
> +
> #ifndef __HAVE_ARCH_STRSTR
> /**
> * strstr - Find the first substring in a %NUL terminated string
[...]
--
Regards,
Pratyush Yadav
Texas Instruments Inc.