From baa9bf9a237fb220465e09267ac820f7302e357f Mon Sep 17 00:00:00 2001
From: Francois Gouget <fgouget@psn.net>
Date: Mon, 27 Dec 1999 05:24:06 +0000
Subject: [PATCH] Buffer overflows and strncpy fixes.

---
 dlls/commdlg/filedlg.c     | 31 +++++++++++++++++--------------
 dlls/commdlg/filetitle.c   |  3 ++-
 dlls/shell32/pidl.c        |  4 ++--
 dlls/shell32/shelllink.c   |  2 +-
 dlls/shell32/shlfolder.c   |  2 +-
 dlls/version/install.c     |  6 ++----
 dlls/winmm/lolvldrv.c      |  5 ++---
 dlls/winmm/wineoss/mixer.c | 12 ++++++------
 files/profile.c            |  8 ++++----
 graphics/psdrv/driver.c    |  8 +++-----
 graphics/psdrv/font.c      |  2 +-
 loader/module.c            |  6 +++---
 loader/ne/module.c         | 10 ++++------
 loader/task.c              |  3 +--
 memory/atom.c              |  6 ++++--
 memory/environ.c           |  3 +--
 misc/lstr.c                |  7 ++++---
 misc/registry.c            |  1 -
 misc/winsock.c             |  8 +++++---
 programs/regapi/regapi.c   | 12 +++++++-----
 relay32/builtin32.c        |  2 +-
 windows/driver.c           |  8 ++++----
 windows/mdi.c              |  3 +--
 windows/x11drv/keyboard.c  |  2 +-
 24 files changed, 77 insertions(+), 77 deletions(-)

diff --git a/dlls/commdlg/filedlg.c b/dlls/commdlg/filedlg.c
index 7380cb25abe..49ae14e5385 100644
--- a/dlls/commdlg/filedlg.c
+++ b/dlls/commdlg/filedlg.c
@@ -129,7 +129,7 @@ static LRESULT WINAPI FileSaveDlgProc(HWND hDlg, UINT msg,
  * Creates a dialog box for the user to select a file to open.
  *
  * RETURNS
- *    TRUE on succes: user selected a valid file
+ *    TRUE on success: user selected a valid file
  *    FALSE on cancel, error, close or filename-does-not-fit-in-buffer.
  *
  * BUGS
@@ -786,9 +786,8 @@ static LONG FILEDLG_WMInitDialog(HWND16 hWnd, WPARAM16 wParam, LPARAM lParam)
   if (lpofn->nFilterIndex == 0 && lpofn->lpstrCustomFilter == (SEGPTR)NULL)
   	lpofn->nFilterIndex = 1;
   SendDlgItemMessage16(hWnd, cmb1, CB_SETCURSEL16, lpofn->nFilterIndex - 1, 0);    
-  strncpy(tmpstr, FILEDLG_GetFileType(PTR_SEG_TO_LIN(lpofn->lpstrCustomFilter),
-	     PTR_SEG_TO_LIN(lpofn->lpstrFilter), lpofn->nFilterIndex - 1),511);
-  tmpstr[511]=0;
+  lstrcpynA(tmpstr, FILEDLG_GetFileType(PTR_SEG_TO_LIN(lpofn->lpstrCustomFilter),
+	     PTR_SEG_TO_LIN(lpofn->lpstrFilter), lpofn->nFilterIndex - 1),512);
   TRACE("nFilterIndex = %ld, SetText of edt1 to '%s'\n", 
   			lpofn->nFilterIndex, tmpstr);
   SetDlgItemTextA( hWnd, edt1, tmpstr );
@@ -798,11 +797,13 @@ static LONG FILEDLG_WMInitDialog(HWND16 hWnd, WPARAM16 wParam, LPARAM lParam)
   /* read initial directory */
   if (PTR_SEG_TO_LIN(lpofn->lpstrInitialDir) != NULL) 
     {
-      strncpy(tmpstr, PTR_SEG_TO_LIN(lpofn->lpstrInitialDir), 510);
-      tmpstr[510]=0;
-      if (strlen(tmpstr) > 0 && tmpstr[strlen(tmpstr)-1] != '\\' 
-	  && tmpstr[strlen(tmpstr)-1] != ':')
-	strcat(tmpstr,"\\");
+      int len;
+      lstrcpynA(tmpstr, PTR_SEG_TO_LIN(lpofn->lpstrInitialDir), 511);
+      len=strlen(tmpstr);
+      if (len > 0 && tmpstr[len-1] != '\\'  && tmpstr[len-1] != ':') {
+        tmpstr[len]='\\';
+        tmpstr[len+1]='\0';
+      }
     }
   else
     *tmpstr = 0;
@@ -926,7 +927,7 @@ static LRESULT FILEDLG_WMCommand(HWND16 hWnd, WPARAM16 wParam, LPARAM lParam)
 	  /* edit control contains wildcards */
 	  if (pstr != NULL)
 	    {
-	      strncpy(tmpstr2, pstr+1, 511); tmpstr2[511]=0;
+	      lstrcpynA(tmpstr2, pstr+1, 512);
 	      *(pstr+1) = 0;
 	    }
 	  else
@@ -973,14 +974,16 @@ static LRESULT FILEDLG_WMCommand(HWND16 hWnd, WPARAM16 wParam, LPARAM lParam)
       ShowWindow16(hWnd, SW_HIDE);   /* this should not be necessary ?! (%%%) */
 #endif
       {
+ 	int lenstr2;
 	int drive = DRIVE_GetCurrentDrive();
 	tmpstr2[0] = 'A'+ drive;
 	tmpstr2[1] = ':';
 	tmpstr2[2] = '\\';
-	strncpy(tmpstr2 + 3, DRIVE_GetDosCwd(drive), 507); tmpstr2[510]=0;
-	if (strlen(tmpstr2) > 3)
-	   strcat(tmpstr2, "\\");
-	strncat(tmpstr2, tmpstr, 511-strlen(tmpstr2)); tmpstr2[511]=0;
+	lstrcpynA(tmpstr2 + 3, DRIVE_GetDosCwd(drive), 507);
+        lenstr2=strlen(tmpstr2);
+	if (lenstr2 > 3)
+ 	   tmpstr2[lenstr2++]='\\';
+	lstrcpynA(tmpstr2+lenstr2, tmpstr, 512-lenstr2);
 	if (lpofn->lpstrFile)
 	  lstrcpynA(PTR_SEG_TO_LIN(lpofn->lpstrFile), tmpstr2,lpofn->nMaxFile);
       }
diff --git a/dlls/commdlg/filetitle.c b/dlls/commdlg/filetitle.c
index 682ad4d9b7a..e4607953cce 100644
--- a/dlls/commdlg/filetitle.c
+++ b/dlls/commdlg/filetitle.c
@@ -62,7 +62,8 @@ short WINAPI GetFileTitleA(LPCSTR lpFile, LPSTR lpTitle, UINT cbBuf)
 	if(cbBuf < len)
 		return len;
 
-	strncpy(lpTitle, &lpFile[i], len);
+       /* The lpTitle buffer is big enough, perform a simple copy */
+	strcpy(lpTitle, &lpFile[i]);
 	return 0;
 }
 
diff --git a/dlls/shell32/pidl.c b/dlls/shell32/pidl.c
index 4717a73c61c..de69ee1206b 100644
--- a/dlls/shell32/pidl.c
+++ b/dlls/shell32/pidl.c
@@ -792,7 +792,7 @@ HRESULT WINAPI SHGetSpecialFolderLocation(
 	INT nFolder,
 	LPITEMIDLIST * ppidl)
 {
-	CHAR		szPath[256];
+	CHAR		szPath[MAX_PATH];
 	HRESULT		hr = E_INVALIDARG;
 
 	TRACE_(shell)("(%04x,0x%x,%p)\n", hwndOwner,nFolder,ppidl);
@@ -1397,7 +1397,7 @@ DWORD _ILSimpleGetText (LPCITEMIDLIST pidl, LPSTR szOut, UINT uOutSize)
 	{
 	  /* filesystem */
 	  if (szOut)
-	    lstrcpynA(szOut, szSrc, MAX_PATH);
+	    lstrcpynA(szOut, szSrc, uOutSize);
 
 	  dwReturn = strlen(szSrc);
 	}
diff --git a/dlls/shell32/shelllink.c b/dlls/shell32/shelllink.c
index 2e78b101ace..4abc2800bdb 100644
--- a/dlls/shell32/shelllink.c
+++ b/dlls/shell32/shelllink.c
@@ -290,7 +290,7 @@ static HRESULT WINAPI IPersistStream_fnLoad(
 	PLINK_HEADER lpLinkHeader = HeapAlloc(GetProcessHeap(), 0, LINK_HEADER_SIZE);
 	ULONG	dwBytesRead;
 	DWORD	ret = E_FAIL;
-	char	sTemp[512];
+	char	sTemp[MAX_PATH];
 	
 	_ICOM_THIS_From_IPersistStream(IShellLinkImpl, iface);
 
diff --git a/dlls/shell32/shlfolder.c b/dlls/shell32/shlfolder.c
index c099c59d418..6ec75c961f0 100644
--- a/dlls/shell32/shlfolder.c
+++ b/dlls/shell32/shlfolder.c
@@ -462,7 +462,7 @@ IShellFolder * IShellFolder_Constructor(
 	    }
 
 	    len = strlen(sf->sMyPath);
-	    _ILSimpleGetText(pidl, sf->sMyPath + len, dwSize - len + 1);
+	    _ILSimpleGetText(pidl, sf->sMyPath + len, dwSize+2 - len);
 	  }
 
 	  TRACE("-- (%p)->(my pidl=%p, my path=%s)\n",sf, sf->absPidl,debugstr_a(sf->sMyPath));
diff --git a/dlls/version/install.c b/dlls/version/install.c
index 812710dbd23..859d5fcae95 100644
--- a/dlls/version/install.c
+++ b/dlls/version/install.c
@@ -276,8 +276,7 @@ DWORD WINAPI VerFindFileA(
 	if(*lpuDestDirLen < destDirSizeReq) {
 	    retval |= VFF_BUFFTOOSMALL;
 	    if (*lpuDestDirLen) {
-	    strncpy(lpszDestDir, destDir, *lpuDestDirLen - 1);
-	    lpszDestDir[*lpuDestDirLen - 1] = '\0';
+	    lstrcpynA(lpszDestDir, destDir, *lpuDestDirLen);
 	}
 	}
 	else
@@ -290,8 +289,7 @@ DWORD WINAPI VerFindFileA(
 	if(*lpuCurDirLen < curDirSizeReq) {
 	    retval |= VFF_BUFFTOOSMALL;
 	    if (*lpuCurDirLen) {
-	    strncpy(lpszCurDir, curDir, *lpuCurDirLen - 1);
-	    lpszCurDir[*lpuCurDirLen - 1] = '\0';
+	    lstrcpynA(lpszCurDir, curDir, *lpuCurDirLen);
 	    }
 	}
 	else
diff --git a/dlls/winmm/lolvldrv.c b/dlls/winmm/lolvldrv.c
index 7dba951f16b..a8258e9e4fa 100644
--- a/dlls/winmm/lolvldrv.c
+++ b/dlls/winmm/lolvldrv.c
@@ -151,8 +151,7 @@ static	BOOL	MMDRV_GetDescription32(const char* fname, char* buf, int buflen)
 #undef A
 
     if (!VerQueryValueA(ptr, "\\StringFileInfo\\040904B0\\ProductName", &val, &u)) E(("Can't get product name\n"));
-    strncpy(buf, val, buflen - 1);
-    buf[buflen - 1] = '\0';
+    lstrcpynA(buf, val, buflen);
 
 #undef E    
     ret = TRUE;
@@ -1889,7 +1888,7 @@ UINT	MMDRV_PhysicalFeatures(LPWINE_MLD mld, UINT uMsg, DWORD dwParam1,
     /* all those function calls are undocumented */
     switch (uMsg) {
     case 0x801: /* DRV_QUERYDRVENTRY */
-	strncpy((LPSTR)dwParam1, lpDrv->name, LOWORD(dwParam2));
+	lstrcpynA((LPSTR)dwParam1, lpDrv->name, LOWORD(dwParam2));
 	break;
     case 0x802: /* DRV_QUERYDEVNODE */
 	*(LPDWORD)dwParam1 = 0L; /* should be DevNode */
diff --git a/dlls/winmm/wineoss/mixer.c b/dlls/winmm/wineoss/mixer.c
index 64083b80987..869a82cc777 100644
--- a/dlls/winmm/wineoss/mixer.c
+++ b/dlls/winmm/wineoss/mixer.c
@@ -184,8 +184,8 @@ static DWORD MIX_GetLineInfo(WORD wDevID, LPMIXERLINEA lpMl, DWORD fdwInfo)
 	lpMl->dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;
 	lpMl->dwSource = 0xFFFFFFFF;
 	lpMl->dwLineID = SOUND_MIXER_VOLUME;
-	strncpy(lpMl->szShortName, MIX_Labels[SOUND_MIXER_VOLUME], MIXER_SHORT_NAME_CHARS);
-	strncpy(lpMl->szName, MIX_Names[SOUND_MIXER_VOLUME], MIXER_LONG_NAME_CHARS);
+	lstrcpynA(lpMl->szShortName, MIX_Labels[SOUND_MIXER_VOLUME], MIXER_SHORT_NAME_CHARS);
+	lstrcpynA(lpMl->szName, MIX_Names[SOUND_MIXER_VOLUME], MIXER_LONG_NAME_CHARS);
 	
 	/* we have all connections found in the MIX_DevMask */
 	lpMl->cConnections = 0;
@@ -337,8 +337,8 @@ static void MIX_DoGetLineControls(LPMIXERCONTROLA mc, DWORD lineID, DWORD dwType
 	mc->dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
 	mc->fdwControl = 0;
 	mc->cMultipleItems = 0;
-	strncpy(mc->szShortName, "Vol", MIXER_SHORT_NAME_CHARS);
-	strncpy(mc->szName, "Volume", MIXER_LONG_NAME_CHARS);
+	lstrcpynA(mc->szShortName, "Vol", MIXER_SHORT_NAME_CHARS);
+	lstrcpynA(mc->szName, "Volume", MIXER_LONG_NAME_CHARS);
 	memset(&mc->Bounds, 0, sizeof(mc->Bounds));
 	/* CONTROLTYPE_VOLUME uses the MIXER_CONTROLDETAILS_UNSIGNED struct, 
 	 * [0, 100] is the range supported by OSS
@@ -356,8 +356,8 @@ static void MIX_DoGetLineControls(LPMIXERCONTROLA mc, DWORD lineID, DWORD dwType
 	mc->dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE;
 	mc->fdwControl = 0;
 	mc->cMultipleItems = 0;
-	strncpy(mc->szShortName, "Mute", MIXER_SHORT_NAME_CHARS);
-	strncpy(mc->szName, "Mute", MIXER_LONG_NAME_CHARS);
+	lstrcpynA(mc->szShortName, "Mute", MIXER_SHORT_NAME_CHARS);
+	lstrcpynA(mc->szName, "Mute", MIXER_LONG_NAME_CHARS);
 	memset(&mc->Bounds, 0, sizeof(mc->Bounds));
 	memset(&mc->Metrics, 0, sizeof(mc->Metrics));
 	break;
diff --git a/files/profile.c b/files/profile.c
index 712b4f3185d..e2629a8ac42 100644
--- a/files/profile.c
+++ b/files/profile.c
@@ -908,7 +908,7 @@ int PROFILE_LoadWineIni(void)
       /* Open -config specified file */
       PROFILE_WineProfile = PROFILE_Load ( f);
       fclose ( f );
-      strncpy(PROFILE_WineIniUsed,Options.configFileName,MAX_PATHNAME_LEN-1);
+      lstrcpynA(PROFILE_WineIniUsed,Options.configFileName,MAX_PATHNAME_LEN);
       return 1;
     }
 
@@ -916,7 +916,7 @@ int PROFILE_LoadWineIni(void)
     {
 	PROFILE_WineProfile = PROFILE_Load( f );
 	fclose( f );
-	strncpy(PROFILE_WineIniUsed,p,MAX_PATHNAME_LEN-1);
+	lstrcpynA(PROFILE_WineIniUsed,p,MAX_PATHNAME_LEN);
 	return 1;
     }
     if ((p = getenv( "HOME" )) != NULL)
@@ -927,7 +927,7 @@ int PROFILE_LoadWineIni(void)
         {
             PROFILE_WineProfile = PROFILE_Load( f );
             fclose( f );
-	    strncpy(PROFILE_WineIniUsed,buffer,MAX_PATHNAME_LEN-1);
+	    lstrcpynA(PROFILE_WineIniUsed,buffer,MAX_PATHNAME_LEN);
             return 1;
         }
     }
@@ -939,7 +939,7 @@ int PROFILE_LoadWineIni(void)
     {
         PROFILE_WineProfile = PROFILE_Load( f );
         fclose( f );
-	strncpy(PROFILE_WineIniUsed,WINE_INI_GLOBAL,MAX_PATHNAME_LEN-1);
+	lstrcpynA(PROFILE_WineIniUsed,WINE_INI_GLOBAL,MAX_PATHNAME_LEN);
         return 1;
     }
     MESSAGE( "Can't open configuration file %s or $HOME%s\n",
diff --git a/graphics/psdrv/driver.c b/graphics/psdrv/driver.c
index c764e6cdff5..b79a3db0ee0 100644
--- a/graphics/psdrv/driver.c
+++ b/graphics/psdrv/driver.c
@@ -113,7 +113,7 @@ void PSDRV_MergeDevmodes(PSDRV_DEVMODEA *dm1, PSDRV_DEVMODEA *dm2,
    if (dm2->dmPublic.dmFields & DM_COLLATE )
        dm1->dmPublic.dmCollate = dm2->dmPublic.dmCollate;
    if (dm2->dmPublic.dmFields & DM_FORMNAME )
-       strncpy(dm1->dmPublic.dmFormName, dm2->dmPublic.dmFormName, CCHFORMNAME);
+       lstrcpynA(dm1->dmPublic.dmFormName, dm2->dmPublic.dmFormName, CCHFORMNAME);
    if (dm2->dmPublic.dmFields & DM_BITSPERPEL )
        dm1->dmPublic.dmBitsPerPel = dm2->dmPublic.dmBitsPerPel;
    if (dm2->dmPublic.dmFields & DM_PELSWIDTH )
@@ -342,8 +342,7 @@ DWORD WINAPI PSDRV_DeviceCapabilities16(LPCSTR lpszDevice, LPCSTR lpszPort,
 
       for(ps = pi->ppd->PageSizes; ps; ps = ps->next, i++)
 	if(lpszOutput != NULL) {
-	  strncpy(cp, ps->FullName, 64);
-	  *(cp + 63) = '\0';
+	  lstrcpynA(cp, ps->FullName, 64);
 	  cp += 64;
 	}
       return i;
@@ -372,8 +371,7 @@ DWORD WINAPI PSDRV_DeviceCapabilities16(LPCSTR lpszDevice, LPCSTR lpszPort,
       
       for(slot = pi->ppd->InputSlots; slot; slot = slot->next, i++)
 	if(lpszOutput != NULL) {
-	  strncpy(cp, slot->FullName, 24);
-	  *(cp + 23) = '\0';
+	  lstrcpynA(cp, slot->FullName, 24);
 	  cp += 24;
 	}
       return i;
diff --git a/graphics/psdrv/font.c b/graphics/psdrv/font.c
index 51a83b5c85f..4e407f24726 100644
--- a/graphics/psdrv/font.c
+++ b/graphics/psdrv/font.c
@@ -288,7 +288,7 @@ static UINT PSDRV_GetFontMetric(DC *dc, AFM *pafm, NEWTEXTMETRIC16 *pTM,
     pTM->tmPitchAndFamily |= TMPF_DEVICE;
     plf->lfPitchAndFamily = 0;
 
-    strncpy( plf->lfFaceName, pafm->FamilyName, LF_FACESIZE );
+    lstrcpynA( plf->lfFaceName, pafm->FamilyName, LF_FACESIZE );
 #undef plf
 
     pTM->tmAscent = pafm->FullAscender * scale;
diff --git a/loader/module.c b/loader/module.c
index e9c73f99cc1..89916f95299 100644
--- a/loader/module.c
+++ b/loader/module.c
@@ -360,7 +360,7 @@ HMODULE MODULE_CreateDummyModule( LPCSTR filename, WORD version )
     NE_MODULE *pModule;
     SEGTABLEENTRY *pSegment;
     char *pStr,*s;
-    int len;
+    unsigned int len;
     const char* basename;
     OFSTRUCT *ofs;
     int of_size, size;
@@ -429,9 +429,9 @@ HMODULE MODULE_CreateDummyModule( LPCSTR filename, WORD version )
     /* Module name */
     pStr = (char *)pSegment;
     pModule->name_table = (int)pStr - (int)pModule;
+    assert(len<256);
     *pStr = len;
-    strncpy( pStr+1, basename, len );
-    pStr[len+1] = 0;
+    lstrcpynA( pStr+1, basename, len+1 );
     pStr += len+2;
 
     /* All tables zero terminated */
diff --git a/loader/ne/module.c b/loader/ne/module.c
index 80153000351..856c18a09c6 100644
--- a/loader/ne/module.c
+++ b/loader/ne/module.c
@@ -1431,7 +1431,7 @@ HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
     HMODULE16	hModule = hFirstModule;
     LPSTR	s;
     BYTE	len, *name_table;
-    char	tmpstr[128];
+    char	tmpstr[MAX_PATH];
     NE_MODULE *pModule;
 
     TRACE("(%s)\n", name);
@@ -1443,8 +1443,7 @@ HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
     if (!len)
     	return 0;
 
-    strncpy(tmpstr, name, sizeof(tmpstr));
-    tmpstr[sizeof(tmpstr)-1] = '\0';
+    lstrcpynA(tmpstr, name, sizeof(tmpstr));
 
     /* If 'name' matches exactly the module name of a module:
      * Return its handle.
@@ -1553,11 +1552,10 @@ static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
     HMODULE16	hModule;
     LPSTR	s, p;
     BYTE	len, *name_table;
-    char	tmpstr[128];
+    char	tmpstr[MAX_PATH];
     NE_MODULE *pModule;
 
-    strncpy(tmpstr, name, sizeof(tmpstr));
-    tmpstr[sizeof(tmpstr)-1] = '\0';
+    lstrcpynA(tmpstr, name, sizeof(tmpstr));
 
     /* If the base filename of 'name' matches the base filename of the module
      * filename of some module (case-insensitive compare):
diff --git a/loader/task.c b/loader/task.c
index 342e17b1de0..118696bf38f 100644
--- a/loader/task.c
+++ b/loader/task.c
@@ -1612,8 +1612,7 @@ BOOL16 WINAPI TaskNext16( TASKENTRY *lpte )
     lpte->wStackBottom  = pInstData->stackbottom;
     lpte->wcEvents      = pTask->nEvents;
     lpte->hQueue        = pTask->hQueue;
-    strncpy( lpte->szModule, pTask->module_name, 8 );
-    lpte->szModule[8]   = '\0';
+    lstrcpynA( lpte->szModule, pTask->module_name, sizeof(lpte->szModule) );
     lpte->wPSPOffset    = 0x100;  /*??*/
     lpte->hNext         = pTask->hNext;
     return TRUE;
diff --git a/memory/atom.c b/memory/atom.c
index 27fbf0b8c73..7ac967af321 100644
--- a/memory/atom.c
+++ b/memory/atom.c
@@ -225,7 +225,7 @@ static ATOM ATOM_AddAtom(
 	    (!lstrncmpiA( entryPtr->str, str, len )))
 	{
 	    entryPtr->refCount++;
-        TRACE("-- existing 0x%x\n", entry);
+            TRACE("-- existing 0x%x\n", entry);
 	    return HANDLETOATOM( entry );
 	}
 	entry = entryPtr->next;
@@ -240,7 +240,9 @@ static ATOM ATOM_AddAtom(
     entryPtr->next = table->entries[hash];
     entryPtr->refCount = 1;
     entryPtr->length = len;
-    strncpy( entryPtr->str, str, ae_len - sizeof(ATOMENTRY) + 1); /* always use strncpy ('\0's padding) */
+    /* Some applications _need_ the '\0' padding provided by this strncpy */
+    strncpy( entryPtr->str, str, ae_len - sizeof(ATOMENTRY) + 1 );
+    entryPtr->str[ae_len - sizeof(ATOMENTRY)] = '\0';
     table->entries[hash] = entry;
     TRACE("-- new 0x%x\n", entry);
     return HANDLETOATOM( entry );
diff --git a/memory/environ.c b/memory/environ.c
index 2893cde405c..ff45b0dc140 100644
--- a/memory/environ.c
+++ b/memory/environ.c
@@ -131,8 +131,7 @@ BOOL ENV_InheritEnvironment( PDB *pdb, LPCSTR env )
 
     /* Copy the environment */
 
-    if (!(pdb->env_db->environ = HeapAlloc( pdb->heap, 0,
-                                            size + EXTRA_ENV_SIZE )))
+    if (!(pdb->env_db->environ = HeapAlloc( pdb->heap, 0, size )))
         return FALSE;
     pdb->env_db->env_sel = SELECTOR_AllocBlock( pdb->env_db->environ,
                                                 0x10000, SEGMENT_DATA,
diff --git a/misc/lstr.c b/misc/lstr.c
index 4f374c2aac2..1637fc4e4a2 100644
--- a/misc/lstr.c
+++ b/misc/lstr.c
@@ -645,7 +645,7 @@ DWORD WINAPI FormatMessage16(
 	allocstring=PTR_SEG_OFF_TO_LIN(CURRENT_DS,*((HLOCAL16*)lpBuffer));
 	memcpy( allocstring,target,talloced);
     } else
-        strncpy(lpBuffer,target,nSize);
+        lstrcpynA(lpBuffer,target,nSize);
     HeapFree(GetProcessHeap(),0,target);
     if (from) HeapFree(GetProcessHeap(),0,from);
     return (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) ? 
@@ -822,8 +822,9 @@ DWORD WINAPI FormatMessageA(
 		/* nSize is the MINIMUM size */
 		*((LPVOID*)lpBuffer) = (LPVOID)LocalAlloc(GMEM_ZEROINIT,talloced);
 		memcpy(*(LPSTR*)lpBuffer,target,talloced);
-	} else
-		strncpy(lpBuffer,target,nSize);
+    } else {
+		lstrcpynA(lpBuffer,target,nSize);
+    }
 	HeapFree(GetProcessHeap(),0,target);
 	if (from) HeapFree(GetProcessHeap(),0,from);
 	return (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) ? 
diff --git a/misc/registry.c b/misc/registry.c
index 2f0407a6d87..afe70ba8987 100644
--- a/misc/registry.c
+++ b/misc/registry.c
@@ -97,7 +97,6 @@ LPWSTR strcvtA2W(LPCSTR src, int nchars)
    LPWSTR dest = xmalloc (2 * nchars + 2);
 
    lstrcpynAtoW(dest,src,nchars+1);
-   dest[nchars] = 0;
    return dest;
 }
 
diff --git a/misc/winsock.c b/misc/winsock.c
index 23cd918d4cd..69bdb2f6d0d 100644
--- a/misc/winsock.c
+++ b/misc/winsock.c
@@ -1142,13 +1142,15 @@ char* WINAPI WINSOCK_inet_ntoa(struct in_addr in)
 	char*	s = inet_ntoa(in);
 	if( s ) 
 	{
-	    if( pwsi->dbuffer == NULL )
-		if((pwsi->dbuffer = (char*) SEGPTR_ALLOC(32)) == NULL )
+            if( pwsi->dbuffer == NULL ) {
+                /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
+		if((pwsi->dbuffer = (char*) SEGPTR_ALLOC(16)) == NULL )
 		{
 		    SetLastError(WSAENOBUFS);
 		    return NULL;
 		}
-	    strncpy(pwsi->dbuffer, s, 32 );
+            }
+	    strcpy(pwsi->dbuffer, s);
 	    return pwsi->dbuffer; 
 	}
 	SetLastError(wsaErrno());
diff --git a/programs/regapi/regapi.c b/programs/regapi/regapi.c
index eef5981aa29..0241c97ef3a 100644
--- a/programs/regapi/regapi.c
+++ b/programs/regapi/regapi.c
@@ -554,8 +554,10 @@ static HRESULT setValue(LPSTR *argv)
       HeapFree(GetProcessHeap(), 0, argv[1]);
       argv[1] = HeapAlloc(GetProcessHeap(), 0, dwSize+1);
 
-      if ( argv[1] != NULL )
+      if ( argv[1] != NULL ) {
         strncpy(argv[1], lpsCurrentValue, dwSize);
+        argv[1][dwSize]='\0';
+    }
     }
 
     return KEY_VALUE_ALREADY_SET;
@@ -707,8 +709,7 @@ static void processQueryValue(LPSTR cmdline)
              (LPBYTE)lpsData,
              &lLen);
 
-    while(hRes==ERROR_MORE_DATA){
-        lLen+=KEY_MAX_LEN;
+    if (hRes==ERROR_MORE_DATA) {
         lpsData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpsData,lLen);
         hRes = RegQueryValue(currentKeyHandle,currentKeyName,(LPBYTE)lpsData,&lLen);
     }
@@ -717,6 +718,7 @@ static void processQueryValue(LPSTR cmdline)
     {
       lpsRes = HeapAlloc( GetProcessHeap(), 0, lLen);
       strncpy(lpsRes, lpsData, lLen);
+      lpsRes[lLen-1]='\0';
     }
   }
   else 
@@ -735,8 +737,7 @@ static void processQueryValue(LPSTR cmdline)
              (LPBYTE)lpbData, 
              &dwLen);
 
-    while(hRes==ERROR_MORE_DATA){
-        dwLen+=KEY_MAX_LEN;
+    if (hRes==ERROR_MORE_DATA) {
         lpbData=HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,lpbData,dwLen);
         hRes = RegQueryValueEx(currentKeyHandle,keyValue,NULL,&dwType,(LPBYTE)lpbData,&dwLen);
     }
@@ -753,6 +754,7 @@ static void processQueryValue(LPSTR cmdline)
         {
           lpsRes = HeapAlloc( GetProcessHeap(), 0, dwLen);
           strncpy(lpsRes, lpbData, dwLen);
+          lpsRes[dwLen-1]='\0';
           break;
         }
         case REG_DWORD:
diff --git a/relay32/builtin32.c b/relay32/builtin32.c
index 480d836f87c..bbbc11e830f 100644
--- a/relay32/builtin32.c
+++ b/relay32/builtin32.c
@@ -424,7 +424,7 @@ WINE_MODREF *BUILTIN32_LoadLibraryExA(LPCSTR path, DWORD flags, DWORD *err)
     HMODULE16      hModule16;
     NE_MODULE     *pModule;
     WINE_MODREF   *wm;
-    char           dllname[256], *p;
+    char           dllname[MAX_PATH], *p;
 
     /* Fix the name in case we have a full path and extension */
     if ((p = strrchr( path, '\\' ))) path = p + 1;
diff --git a/windows/driver.c b/windows/driver.c
index d978b1dc4ac..30894c83048 100644
--- a/windows/driver.c
+++ b/windows/driver.c
@@ -669,7 +669,7 @@ LPWINE_DRIVER DRIVER_RegisterDriver16(LPCSTR lpName, HMODULE16 hModule, DRIVERPR
 	lpDrv->dwFlags         = WINE_DI_TYPE_16;
 	lpDrv->dwDriverID      = 0;
 	lpDrv->hDriver16       = DRIVER_CreateDrvr16();
-	strncpy(lpDrv->szAliasName, lpName, sizeof(lpDrv->szAliasName));
+	lstrcpynA(lpDrv->szAliasName, lpName, sizeof(lpDrv->szAliasName));
 	lpDrv->d.d16.hModule   = hModule;
 	lpDrv->d.d16.lpDrvProc = lpProc;
 	
@@ -697,7 +697,7 @@ LPWINE_DRIVER DRIVER_RegisterDriver32(LPCSTR lpName, HMODULE hModule, DRIVERPROC
 	lpDrv->dwFlags          = WINE_DI_TYPE_32;
 	lpDrv->dwDriverID       = 0;
 	lpDrv->hDriver16        = DRIVER_CreateDrvr16();
-	strncpy(lpDrv->szAliasName, lpName, sizeof(lpDrv->szAliasName));
+	lstrcpynA(lpDrv->szAliasName, lpName, sizeof(lpDrv->szAliasName));
 	lpDrv->d.d32.hModule    = hModule;
 	lpDrv->d.d32.lpDrvProc  = lpProc;
 	
@@ -819,7 +819,7 @@ HDRVR WINAPI OpenDriverA(LPCSTR lpDriverName, LPCSTR lpSectionName, LPARAM lPara
     TRACE("('%s', '%s', %08lX);\n", lpDriverName, lpSectionName, lParam);
     
     if (lpSectionName == NULL) {
-	strncpy(drvName, lpDriverName, sizeof(drvName));
+	lstrcpynA(drvName, lpDriverName, sizeof(drvName));
 	hDriver = DRIVER_TryOpenDriver32(lpDriverName, lParam, TRUE);
 	if (!hDriver) {
 	    hDriver = DRIVER_TryOpenDriver16(lpDriverName, lParam, TRUE);
@@ -979,7 +979,7 @@ BOOL16 WINAPI GetDriverInfo16(HDRVR16 hDrvr, LPDRIVERINFOSTRUCT16 lpDrvInfo)
 	(lpDrv->dwFlags & WINE_DI_TYPE_MASK) == WINE_DI_TYPE_16) {
 	lpDrvInfo->hDriver = lpDrv->hDriver16;
 	lpDrvInfo->hModule = lpDrv->d.d16.hModule;
-	strncpy(lpDrvInfo->szAliasName, lpDrv->szAliasName, sizeof(lpDrvInfo->szAliasName));
+	lstrcpynA(lpDrvInfo->szAliasName, lpDrv->szAliasName, sizeof(lpDrvInfo->szAliasName));
 	ret = TRUE;
     }
     
diff --git a/windows/mdi.c b/windows/mdi.c
index b67ada10d4d..6b85a6f2bc8 100644
--- a/windows/mdi.c
+++ b/windows/mdi.c
@@ -1028,8 +1028,7 @@ static void MDI_UpdateFrameText( WND *frameWnd, HWND hClient,
 	}
 	else
 	{
-            strncpy(lpBuffer, ci->frameTitle, MDI_MAXTITLELENGTH );
-	    lpBuffer[MDI_MAXTITLELENGTH]='\0';
+            lstrcpynA(lpBuffer, ci->frameTitle, MDI_MAXTITLELENGTH+1 );
 	}
         WIN_ReleaseWndPtr(childWnd);
 
diff --git a/windows/x11drv/keyboard.c b/windows/x11drv/keyboard.c
index 41a9c0d0395..6bcc6ea090d 100644
--- a/windows/x11drv/keyboard.c
+++ b/windows/x11drv/keyboard.c
@@ -1153,7 +1153,7 @@ INT16 X11DRV_KEYBOARD_GetKeyNameText(LONG lParam, LPSTR lpBuffer, INT16 nSize)
             scanCode, keyc, (int)keys, name);
       if (lpBuffer && nSize && name)
       {
-          strncpy(lpBuffer, name, nSize);
+          lstrcpynA(lpBuffer, name, nSize);
           return 1;
       }
   }
-- 
GitLab