delorie.com/archives/browse.cgi   search  
Mail Archives: geda-user/2023/02/02/18:11:41

X-Authentication-Warning: delorie.com: mail set sender to geda-user-bounces using -f
X-Recipient: geda-user AT delorie DOT com
X-Mailer: exmh version 2.8.0 04/21/2012 with nmh-1.7+dev
X-Exmh-Isig-CompType: repl
X-Exmh-Isig-Folder: inbox
From: "karl AT aspodata DOT se [via geda-user AT delorie DOT com]" <geda-user AT delorie DOT com>
To: geda-user AT delorie DOT com
Subject: Re: [geda-user] strncpy in pcb
In-reply-to: <xn7cx02cph.fsf@envy.delorie.com>
References: <xn7cx02cph DOT fsf AT envy DOT delorie DOT com>
Comments: In-reply-to DJ Delorie <dj AT delorie DOT com>
message dated "Thu, 02 Feb 2023 12:34:34 -0500."
Mime-Version: 1.0
Message-Id: <20230202225152.3539085E50B5@turkos.aspodata.se>
Date: Thu, 2 Feb 2023 23:51:52 +0100 (CET)
X-Virus-Scanned: ClamAV using ClamSMTP
Reply-To: geda-user AT delorie DOT com
Errors-To: nobody AT delorie DOT com
X-Mailing-List: geda-user AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

DJ Delorie:
> "karl AT aspodata DOT se [via geda-user AT delorie DOT com]" <geda-user AT delorie DOT com>
> writes:
> > Generally, it would be best to use the form:
> >  strncpy(dst,src,sizeof(dst)-1)
> 
> The problem with strncpy is that it doesn't always NUL-terminate the
> destination, even in the case above.  If the source string length
> happens to be the same as the specified size, no NUL is written, you
> have a non-terminated string, and it's a security issue assuming it
> doesn't just crash.

Well, add a dst[sizeof(dst)-1] = '\0' then.

> What is needed is a function that:
> 
> 1. Copies the whole string, including NUL, if it fits, or
> 
> 2. Fails safely if it doesn't.
> 
> strncpy can't be made to do that.  Neither can strlcpy for that matter.
> strcpy_s can but it isn't generally available yet.

should it handle overlapping strings ?

> What we need is something like:
> 
> pcb_strcpy (s, d, l)
> {
>   i = strlen(s);
>   if (i+1 <= l)
>     memcpy (s, d, i+1)
>   else
>     abort()
> }

I'm not found of abort(). It's ok if you are developing, else you should
fail gracefully.

int  pcb_strcpy(src, dst, dsz) {
  if (!dst || !dsz) return -1;
  if (!src) return 0;
  size_t src_len = strlen(src);
  if (src_len+1 > dsz) return -2;

  if (src < dst && src+src_len >= dst) return -3;
  if (dst+src_len+1 >= src) return -4;

  memcpy(src,dst,src_len+1);
  return src_len;
}

Then one needs some support to handle return values.
My take on that is:
 https://aspodata.se/git/c/libaspoutil/log_util.h

Regards,
/Karl Hammar


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019