diff mbox series

[kvm-unit-tests,1/3] lib/string: Fix getenv name matching

Message ID 20201014191444.136782-2-drjones@redhat.com
State New, archived
Headers show
Series A few miscellaneous fixes | expand

Commit Message

Andrew Jones Oct. 14, 2020, 7:14 p.m. UTC
Without confirming that the name length exactly matches too, then
the string comparison would return the same value for VAR* as for
VAR, when VAR came first in the environ array.

Signed-off-by: Andrew Jones <drjones@redhat.com>
---
 lib/string.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

Comments

Thomas Huth Oct. 15, 2020, 8:19 a.m. UTC | #1
On 14/10/2020 21.14, Andrew Jones wrote:
> Without confirming that the name length exactly matches too, then
> the string comparison would return the same value for VAR* as for
> VAR, when VAR came first in the environ array.
> 
> Signed-off-by: Andrew Jones <drjones@redhat.com>
> ---
>  lib/string.c | 5 ++++-
>  1 file changed, 4 insertions(+), 1 deletion(-)
> 
> diff --git a/lib/string.c b/lib/string.c
> index 018dcc879516..3a0562120f12 100644
> --- a/lib/string.c
> +++ b/lib/string.c
> @@ -171,10 +171,13 @@ extern char **environ;
>  char *getenv(const char *name)
>  {
>      char **envp = environ, *delim;
> +    int len;
>  
>      while (*envp) {
>          delim = strchr(*envp, '=');
> -        if (delim && strncmp(name, *envp, delim - *envp) == 0)
> +        assert(delim);
> +        len = delim - *envp;
> +        if (strlen(name) == len && strncmp(name, *envp, len) == 0)
>              return delim + 1;
>          ++envp;
>      }
> 

Reviewed-by: Thomas Huth <thuth@redhat.com>
Paolo Bonzini Oct. 31, 2020, 2:31 p.m. UTC | #2
On 14/10/20 21:14, Andrew Jones wrote:
> +        if (strlen(name) == len && strncmp(name, *envp, len) == 0)
>              return delim + 1;
>          ++envp;
>      }
> -- 2.26.2


Slightly more efficient:

+        if (memcmp(name, *envp, len) == 0 && !name[len])

(strncmp is not needed since we know there's no NULL between *envp and
*envp+len, and after memcmp we know the same about the first len
characters of name).

Paolo
diff mbox series

Patch

diff --git a/lib/string.c b/lib/string.c
index 018dcc879516..3a0562120f12 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -171,10 +171,13 @@  extern char **environ;
 char *getenv(const char *name)
 {
     char **envp = environ, *delim;
+    int len;
 
     while (*envp) {
         delim = strchr(*envp, '=');
-        if (delim && strncmp(name, *envp, delim - *envp) == 0)
+        assert(delim);
+        len = delim - *envp;
+        if (strlen(name) == len && strncmp(name, *envp, len) == 0)
             return delim + 1;
         ++envp;
     }