public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [PATCH v3 0/6] Refine type cast for pointer subtraction
@ 2017-02-25  4:05 Hao Wu
  2017-02-25  4:05 ` [PATCH v3 1/6] MdeModulePkg: " Hao Wu
                   ` (5 more replies)
  0 siblings, 6 replies; 18+ messages in thread
From: Hao Wu @ 2017-02-25  4:05 UTC (permalink / raw)
  To: edk2-devel; +Cc: Hao Wu

V3:
Send out the full patch series for review.

V2 refines the commit messages:
For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object; the
result is the difference of the subscripts of the two array elements. The
size of the result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
is not representable in an object of that type, the behavior is
undefined."

In our codes, there are cases that the pointer subtraction is not
performed by pointers to elements of the same array object. This might
lead to potential issues, since the behavior is undefined according to C11
standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some
static code checkers may warn that the pointer subtraction might underflow
first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each
pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;


V1:
For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 spec, ptrdiff_t is a signed integer type but its size is
implementation-defined.

There are cases that the result of pointer subtraction is type casted to
UINTN, like:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

Some static code checkers may warn that the pointer subtraction might
overflow first and then the result is being cast to a bigger size.

The series will cast each pointer to UINTN first and then perform the
subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;


Hao Wu (6):
  MdeModulePkg: Refine type cast for pointer subtraction
  CryptoPkg: Refine type cast for pointer subtraction
  IntelFrameworkModulePkg: Refine type cast for pointer subtraction
  NetworkPkg: Refine type cast for pointer subtraction
  SecurityPkg: Refine type cast for pointer subtraction
  ShellPkg: Refine type cast for pointer subtraction

 CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c                |  6 +++---
 IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c                        |  4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c                      |  4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c                   |  4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c                      |  4 ++--
 IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c              |  4 ++--
 IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c              |  6 +++---
 MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c                         |  4 ++--
 MdeModulePkg/Include/Library/NetLib.h                                        |  6 +++---
 MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c                        |  4 ++--
 MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c                    |  2 +-
 MdeModulePkg/Library/FileExplorerLib/FileExplorer.c                          |  4 ++--
 MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c                   |  4 ++--
 MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c                       |  4 ++--
 MdeModulePkg/Universal/DebugPortDxe/DebugPort.c                              |  4 ++--
 MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c            |  4 ++--
 MdeModulePkg/Universal/HiiDatabaseDxe/Image.c                                |  4 ++--
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c                        | 10 +++++-----
 NetworkPkg/HttpDxe/HttpImpl.c                                                |  4 ++--
 SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c        | 16 ++++++++--------
 SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c              | 10 +++++-----
 SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c                                |  6 +++---
 SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c                                  | 10 +++++-----
 SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c                                  | 10 +++++-----
 SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c | 12 ++++++------
 ShellPkg/Application/Shell/ShellParametersProtocol.c                         |  6 +++---
 ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c                       |  4 ++--
 ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c          |  4 ++--
 ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c                            |  4 ++--
 ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c                             |  4 ++--
 30 files changed, 86 insertions(+), 86 deletions(-)

-- 
1.9.5.msysgit.0



^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH v3 1/6] MdeModulePkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 [PATCH v3 0/6] Refine type cast for pointer subtraction Hao Wu
@ 2017-02-25  4:05 ` Hao Wu
  2017-03-06  1:37   ` Tian, Feng
  2017-02-25  4:05 ` [PATCH v3 2/6] CryptoPkg: " Hao Wu
                   ` (4 subsequent siblings)
  5 siblings, 1 reply; 18+ messages in thread
From: Hao Wu @ 2017-02-25  4:05 UTC (permalink / raw)
  To: edk2-devel; +Cc: Hao Wu, Feng Tian, Star Zeng

For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object; the
result is the difference of the subscripts of the two array elements. The
size of the result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
is not representable in an object of that type, the behavior is
undefined."

In our codes, there are cases that the pointer subtraction is not
performed by pointers to elements of the same array object. This might
lead to potential issues, since the behavior is undefined according to C11
standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some
static code checkers may warn that the pointer subtraction might underflow
first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each
pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Feng Tian <feng.tian@intel.com>
Cc: Star Zeng <star.zeng@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c              |  4 ++--
 MdeModulePkg/Include/Library/NetLib.h                             |  6 +++---
 MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c             |  4 ++--
 MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c         |  2 +-
 MdeModulePkg/Library/FileExplorerLib/FileExplorer.c               |  4 ++--
 MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c        |  4 ++--
 MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c            |  4 ++--
 MdeModulePkg/Universal/DebugPortDxe/DebugPort.c                   |  4 ++--
 MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c |  4 ++--
 MdeModulePkg/Universal/HiiDatabaseDxe/Image.c                     |  4 ++--
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c             | 10 +++++-----
 11 files changed, 25 insertions(+), 25 deletions(-)

diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c
index 2bc4f8c..d2ad94e 100644
--- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c
+++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c
@@ -1,7 +1,7 @@
 /** @file
   PCI Rom supporting funtions implementation for PCI Bus module.
 
-Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -776,7 +776,7 @@ ProcessOpRomImage (
 NextImage:
     RomBarOffset += ImageSize;
 
-  } while (((Indicator & 0x80) == 0x00) && ((UINTN) (RomBarOffset - (UINT8 *) RomBar) < PciDevice->RomSize));
+  } while (((Indicator & 0x80) == 0x00) && (((UINTN) RomBarOffset - (UINTN) RomBar) < PciDevice->RomSize));
 
   return RetStatus;
 }
diff --git a/MdeModulePkg/Include/Library/NetLib.h b/MdeModulePkg/Include/Library/NetLib.h
index 09ead09..3b8ff1a 100644
--- a/MdeModulePkg/Include/Library/NetLib.h
+++ b/MdeModulePkg/Include/Library/NetLib.h
@@ -2,7 +2,7 @@
   This library is only intended to be used by UEFI network stack modules.
   It provides basic functions for the UEFI network stack.
 
-Copyright (c) 2005 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at<BR>
@@ -1610,10 +1610,10 @@ typedef struct {
   (sizeof (NET_BUF) + ((BlockOpNum) - 1) * sizeof (NET_BLOCK_OP))
 
 #define NET_HEADSPACE(BlockOp)  \
-  (UINTN)((BlockOp)->Head - (BlockOp)->BlockHead)
+  ((UINTN)((BlockOp)->Head) - (UINTN)((BlockOp)->BlockHead))
 
 #define NET_TAILSPACE(BlockOp)  \
-  (UINTN)((BlockOp)->BlockTail - (BlockOp)->Tail)
+  ((UINTN)((BlockOp)->BlockTail) - (UINTN)((BlockOp)->Tail))
 
 /**
   Allocate a single block NET_BUF. Upon allocation, all the
diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c
index 71e05bd..d7abcc8 100644
--- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c
+++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c
@@ -10,7 +10,7 @@
   ValidateFmpCapsule(), DisplayCapsuleImage(), ConvertBmpToGopBlt() will
   receive untrusted input and do basic validation.
 
-  Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
   This program and the accompanying materials
   are licensed and made available under the terms and conditions of the BSD License
   which accompanies this distribution.  The full text of the license may be found at
@@ -547,7 +547,7 @@ ConvertBmpToGopBlt (
 
     }
 
-    ImageIndex = (UINTN) (Image - ImageHeader);
+    ImageIndex = (UINTN) Image - (UINTN) ImageHeader;
     if ((ImageIndex % 4) != 0) {
       //
       // Bmp Image starts each row on a 32-bit boundary!
diff --git a/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c b/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c
index 589d4db..d9aeb92 100644
--- a/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c
+++ b/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c
@@ -226,7 +226,7 @@ DxePrintLibPrint2ProtocolVaListToBaseList (
     //
     // If BASE_LIST is larger than Size, then return FALSE
     //
-    if ((UINTN)((UINT8 *)BaseListMarker - (UINT8 *)BaseListStart) > Size) {
+    if (((UINTN)BaseListMarker - (UINTN)BaseListStart) > Size) {
       DEBUG ((DEBUG_ERROR, "The input variable argument list is too long. Please consider breaking into multiple print calls.\n"));
       return FALSE;
     }
diff --git a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c
index 5eedad7..9182751 100644
--- a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c
+++ b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c
@@ -728,7 +728,7 @@ LibAppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 3);
-      StrCpyS (LastSlash, MaxLen - (UINTN) (LastSlash - Str), TmpStr);
+      StrCpyS (LastSlash, MaxLen - ((UINTN) LastSlash - (UINTN) Str) / sizeof (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '\\') {
       //
@@ -740,7 +740,7 @@ LibAppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 2);
-      StrCpyS (Ptr, MaxLen - (UINTN) (Ptr - Str), TmpStr);
+      StrCpyS (Ptr, MaxLen - ((UINTN) Ptr - (UINTN) Str) / sizeof (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\') {
       LastSlash = Ptr;
diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c
index 5698c91..1f8aaf4 100644
--- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c
+++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c
@@ -1,7 +1,7 @@
 /** @file
   Save the S3 data to S3 boot script.
 
-  Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 
   This program and the accompanying materials
   are licensed and made available under the terms and conditions
@@ -2025,7 +2025,7 @@ S3BootScriptCalculateInsertAddress (
    // calculate the Position offset
    //
    if (Position != NULL) {
-     PositionOffset = (UINTN) ((UINT8 *)Position - S3TableBase);
+     PositionOffset = (UINTN)Position - (UINTN)S3TableBase;
 
      //
      // If the BeforeOrAfter is FALSE, that means to insert the node right after the node.
diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c b/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c
index 6f705bd..116cf28 100644
--- a/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c
+++ b/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c
@@ -1,7 +1,7 @@
 /** @file
   Load option library functions which relate with creating and processing load options.
 
-Copyright (c) 2011 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2017, Intel Corporation. All rights reserved.<BR>
 (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
@@ -912,7 +912,7 @@ EfiBootManagerVariableToLoadOptionEx (
   FilePath = (EFI_DEVICE_PATH_PROTOCOL *) VariablePtr;
   VariablePtr += FilePathSize;
 
-  OptionalDataSize = (UINT32) (VariableSize - (UINTN) (VariablePtr - Variable));
+  OptionalDataSize = (UINT32) (VariableSize - ((UINTN) VariablePtr - (UINTN) Variable));
   if (OptionalDataSize == 0) {
     OptionalData = NULL;
   } else {
diff --git a/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c b/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c
index 298b6b2..dcb623c 100644
--- a/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c
+++ b/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c
@@ -4,7 +4,7 @@
   ALL CODE IN THE SERIALIO STACK MUST BE RE-ENTRANT AND CALLABLE FROM
   INTERRUPT CONTEXT
 
-Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -569,7 +569,7 @@ DebugPortRead (
     LocalBufferSize = *BufferSize - (BufferPtr - (UINT8 *) Buffer);
   } while (LocalBufferSize != 0 && Timeout > 0);
 
-  *BufferSize = (UINTN) (BufferPtr - (UINT8 *) Buffer);
+  *BufferSize = (UINTN) BufferPtr - (UINTN) Buffer;
 
   return Status;
 }
diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c
index 2e3e8c7..49e747b 100644
--- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c
+++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c
@@ -3,7 +3,7 @@
   These are the common Fault Tolerant Write (FTW) functions that are shared 
   by DXE FTW driver and SMM FTW driver.
 
-Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials                          
 are licensed and made available under the terms and conditions of the BSD License         
 which accompanies this distribution.  The full text of the license may be found at        
@@ -373,7 +373,7 @@ FtwWrite (
   //
   // If Record is out of the range of Header, return access denied.
   //
-  if (((UINTN)((UINT8 *) Record - (UINT8 *) Header)) > FTW_WRITE_TOTAL_SIZE (Header->NumberOfWrites - 1, Header->PrivateDataSize)) {
+  if (((UINTN) Record - (UINTN) Header) > FTW_WRITE_TOTAL_SIZE (Header->NumberOfWrites - 1, Header->PrivateDataSize)) {
     return EFI_ACCESS_DENIED;
   }
 
diff --git a/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c b/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c
index 1668828..e2fa16e 100644
--- a/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c
+++ b/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c
@@ -2,7 +2,7 @@
 Implementation for EFI_HII_IMAGE_PROTOCOL.
 
 
-Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -1124,7 +1124,7 @@ HiiSetImage (
     return EFI_OUT_OF_RESOURCES;
   }
 
-  Part1Size = (UINT32) (UINTN) ((UINT8 *) CurrentImageBlock - (UINT8 *) ImagePackage->ImageBlock);
+  Part1Size = (UINT32) ((UINTN) CurrentImageBlock - (UINTN) ImagePackage->ImageBlock);
   Part2Size = ImagePackage->ImageBlockSize - Part1Size - OldBlockSize;
   CopyMem (ImageBlocks, ImagePackage->ImageBlock, Part1Size);
 
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index f5b6a5f..b0c7434 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -16,7 +16,7 @@
   VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow,
   integer overflow. It should also check attribute to avoid authentication bypass.
 
-Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
@@ -1170,7 +1170,7 @@ Reclaim (
   // Install the new variable if it is not NULL.
   //
   if (NewVariable != NULL) {
-    if ((UINTN) (CurrPtr - ValidBuffer) + NewVariableSize > VariableStoreHeader->Size) {
+    if (((UINTN) CurrPtr - (UINTN) ValidBuffer) + NewVariableSize > VariableStoreHeader->Size) {
       //
       // No enough space to store the new variable.
       //
@@ -1211,8 +1211,8 @@ Reclaim (
     // If volatile variable store, just copy valid buffer.
     //
     SetMem ((UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size, 0xff);
-    CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - ValidBuffer));
-    *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);
+    CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) CurrPtr - (UINTN) ValidBuffer);
+    *LastVariableOffset = (UINTN) CurrPtr - (UINTN) ValidBuffer;
     Status  = EFI_SUCCESS;
   } else {
     //
@@ -1223,7 +1223,7 @@ Reclaim (
               (VARIABLE_STORE_HEADER *) ValidBuffer
               );
     if (!EFI_ERROR (Status)) {
-      *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);
+      *LastVariableOffset = (UINTN) CurrPtr - (UINTN) ValidBuffer;
       mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;
       mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;
       mVariableModuleGlobal->CommonUserVariableTotalSize = CommonUserVariableTotalSize;
-- 
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v3 2/6] CryptoPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 [PATCH v3 0/6] Refine type cast for pointer subtraction Hao Wu
  2017-02-25  4:05 ` [PATCH v3 1/6] MdeModulePkg: " Hao Wu
@ 2017-02-25  4:05 ` Hao Wu
  2017-02-27  2:23   ` Long, Qin
  2017-02-25  4:05 ` [PATCH v3 3/6] IntelFrameworkModulePkg: " Hao Wu
                   ` (3 subsequent siblings)
  5 siblings, 1 reply; 18+ messages in thread
From: Hao Wu @ 2017-02-25  4:05 UTC (permalink / raw)
  To: edk2-devel; +Cc: Hao Wu, Qin Long, Ting Ye

For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object; the
result is the difference of the subscripts of the two array elements. The
size of the result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
is not representable in an object of that type, the behavior is
undefined."

In our codes, there are cases that the pointer subtraction is not
performed by pointers to elements of the same array object. This might
lead to potential issues, since the behavior is undefined according to C11
standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some
static code checkers may warn that the pointer subtraction might underflow
first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each
pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Qin Long <qin.long@intel.com>
Cc: Ting Ye <ting.ye@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c b/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c
index 19c30dc..feaa371 100644
--- a/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c
+++ b/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c
@@ -2,7 +2,7 @@
   Light-weight Memory Management Routines for OpenSSL-based Crypto
   Library at Runtime Phase.
 
-Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -282,7 +282,7 @@ RuntimeFreeMem (
   UINTN  StartOffset;
   UINTN  StartPageIndex;
 
-  StartOffset    = (UINTN) ((UINT8 *)Buffer - mRTPageTable->DataAreaBase);
+  StartOffset    = (UINTN)Buffer - (UINTN)mRTPageTable->DataAreaBase;
   StartPageIndex = RT_SIZE_TO_PAGES (mRTPageTable->Pages[RT_SIZE_TO_PAGES(StartOffset)].StartPageOffset);
 
   while (StartPageIndex < mRTPageTable->PageCount) {
@@ -403,7 +403,7 @@ void *realloc (void *ptr, size_t size)
   //
   // Get Original Size of ptr
   //
-  StartOffset    = (UINTN) ((UINT8 *)ptr - mRTPageTable->DataAreaBase);
+  StartOffset    = (UINTN)ptr - (UINTN)mRTPageTable->DataAreaBase;
   StartPageIndex = RT_SIZE_TO_PAGES (mRTPageTable->Pages[RT_SIZE_TO_PAGES (StartOffset)].StartPageOffset);
   PageCount      = 0;
   while (StartPageIndex < mRTPageTable->PageCount) {
-- 
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v3 3/6] IntelFrameworkModulePkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 [PATCH v3 0/6] Refine type cast for pointer subtraction Hao Wu
  2017-02-25  4:05 ` [PATCH v3 1/6] MdeModulePkg: " Hao Wu
  2017-02-25  4:05 ` [PATCH v3 2/6] CryptoPkg: " Hao Wu
@ 2017-02-25  4:05 ` Hao Wu
  2017-02-27  6:59   ` Fan, Jeff
  2017-02-25  4:05 ` [PATCH v3 4/6] NetworkPkg: " Hao Wu
                   ` (2 subsequent siblings)
  5 siblings, 1 reply; 18+ messages in thread
From: Hao Wu @ 2017-02-25  4:05 UTC (permalink / raw)
  To: edk2-devel; +Cc: Hao Wu, Jeff Fan

For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object; the
result is the difference of the subscripts of the two array elements. The
size of the result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
is not representable in an object of that type, the behavior is
undefined."

In our codes, there are cases that the pointer subtraction is not
performed by pointers to elements of the same array object. This might
lead to potential issues, since the behavior is undefined according to C11
standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some
static code checkers may warn that the pointer subtraction might underflow
first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each
pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Jeff Fan <jeff.fan@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c           | 4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c         | 4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c      | 4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c         | 4 ++--
 IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c | 4 ++--
 IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c | 6 +++---
 6 files changed, 13 insertions(+), 13 deletions(-)

diff --git a/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c b/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
index 8f91a7d..c4c77ec 100644
--- a/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
+++ b/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
@@ -1,6 +1,6 @@
 /** @file
 
-Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 
 This program and the accompanying materials
 are licensed and made available under the terms and conditions
@@ -318,7 +318,7 @@ GetPciLegacyRom (
       break;
     }
 
-    if ((UINTN)(RomHeader.Raw - (UINT8 *) *Rom) + Pcir->ImageLength * 512 > *ImageSize) {
+    if (((UINTN)RomHeader.Raw - (UINTN)*Rom) + Pcir->ImageLength * 512 > *ImageSize) {
       break;
     }
     
diff --git a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
index bba62a8..628424d 100644
--- a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
+++ b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
@@ -1,7 +1,7 @@
 /** @file
   BDS Lib functions which relate with create or process the boot option.
 
-Copyright (c) 2004 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -1034,7 +1034,7 @@ BdsCreateDevOrder (
   DevOrderPtr->Length  = (UINT16) (sizeof (UINT16) + BEVCount * sizeof (UINT16));
   DevOrderPtr          = (LEGACY_DEV_ORDER_ENTRY *) BdsFillDevOrderBuf (BbsTable, BBS_BEV_DEVICE, BbsCount, DevOrderPtr->Data);
 
-  ASSERT (TotalSize == (UINTN) ((UINT8 *) DevOrderPtr - (UINT8 *) DevOrder));
+  ASSERT (TotalSize == ((UINTN) DevOrderPtr - (UINTN) DevOrder));
 
   //
   // Save device order for legacy boot device to variable.
diff --git a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c
index 1020e84..8f273ff 100644
--- a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c
+++ b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c
@@ -1,7 +1,7 @@
 /** @file
   BDS Lib functions which contain all the code to connect console device
 
-Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -873,7 +873,7 @@ ConvertBmpToGopBlt (
 
     }
 
-    ImageIndex = (UINTN) (Image - ImageHeader);
+    ImageIndex = (UINTN)Image - (UINTN)ImageHeader;
     if ((ImageIndex % 4) != 0) {
       //
       // Bmp Image starts each row on a 32-bit boundary!
diff --git a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c
index 24c1998..2ba511a 100644
--- a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c
+++ b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c
@@ -1,7 +1,7 @@
 /** @file
   Misc BDS library function
 
-Copyright (c) 2004 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -669,7 +669,7 @@ BdsLibVariableToOption (
   // Get load opion data.
   //
   LoadOptions     = TempPtr;
-  LoadOptionsSize = (UINT32) (VariableSize - (UINTN) (TempPtr - Variable));
+  LoadOptionsSize = (UINT32) (VariableSize - ((UINTN)TempPtr - (UINTN)Variable));
 
   //
   // The Console variables may have multiple device paths, so make
diff --git a/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c b/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c
index c56a878..080a436 100644
--- a/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c
+++ b/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c
@@ -3,7 +3,7 @@
   and manage the legacy boot option, all legacy boot option is getting from
   the legacy BBS table.
 
-Copyright (c) 2011 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -725,7 +725,7 @@ LegacyBmCreateDevOrder (
   DevOrderPtr->Length  = (UINT16) (sizeof (UINT16) + BEVCount * sizeof (UINT16));
   DevOrderPtr          = (LEGACY_DEV_ORDER_ENTRY *) LegacyBmFillDevOrderBuf (BbsTable, BBS_BEV_DEVICE, BbsCount, DevOrderPtr->Data);
 
-  ASSERT (TotalSize == (UINTN) ((UINT8 *) DevOrderPtr - (UINT8 *) DevOrder));
+  ASSERT (TotalSize == ((UINTN) DevOrderPtr - (UINTN) DevOrder));
 
   //
   // Save device order for legacy boot device to variable.
diff --git a/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c b/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
index 5898fb3..6233a11 100644
--- a/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
+++ b/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
@@ -5,7 +5,7 @@
 
   Boot option manipulation
 
-Copyright (c) 2004 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -1124,7 +1124,7 @@ BOpt_AppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 3);
-      StrCpyS (LastSlash, MaxLen - (UINTN) (LastSlash - Str), TmpStr);
+      StrCpyS (LastSlash, MaxLen - ((UINTN) LastSlash - (UINTN) Str) / sizeof (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '\\') {
       //
@@ -1136,7 +1136,7 @@ BOpt_AppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 2);
-      StrCpyS (Ptr, MaxLen - (UINTN) (Ptr - Str), TmpStr);
+      StrCpyS (Ptr, MaxLen - ((UINTN) Ptr - (UINTN) Str) / sizeof (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\') {
       LastSlash = Ptr;
-- 
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v3 4/6] NetworkPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 [PATCH v3 0/6] Refine type cast for pointer subtraction Hao Wu
                   ` (2 preceding siblings ...)
  2017-02-25  4:05 ` [PATCH v3 3/6] IntelFrameworkModulePkg: " Hao Wu
@ 2017-02-25  4:05 ` Hao Wu
  2017-03-06  1:03   ` Fu, Siyuan
  2017-03-06  1:14   ` Wu, Jiaxin
  2017-02-25  4:05 ` [PATCH v3 5/6] SecurityPkg: " Hao Wu
  2017-02-25  4:05 ` [PATCH v3 6/6] ShellPkg: " Hao Wu
  5 siblings, 2 replies; 18+ messages in thread
From: Hao Wu @ 2017-02-25  4:05 UTC (permalink / raw)
  To: edk2-devel; +Cc: Hao Wu, Siyuan Fu, Jiaxin Wu

For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object; the
result is the difference of the subscripts of the two array elements. The
size of the result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
is not representable in an object of that type, the behavior is
undefined."

In our codes, there are cases that the pointer subtraction is not
performed by pointers to elements of the same array object. This might
lead to potential issues, since the behavior is undefined according to C11
standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some
static code checkers may warn that the pointer subtraction might underflow
first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each
pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Siyuan Fu <siyuan.fu@intel.com>
Cc: Jiaxin Wu <jiaxin.wu@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 NetworkPkg/HttpDxe/HttpImpl.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/NetworkPkg/HttpDxe/HttpImpl.c b/NetworkPkg/HttpDxe/HttpImpl.c
index 745832b..1f7a4fa 100644
--- a/NetworkPkg/HttpDxe/HttpImpl.c
+++ b/NetworkPkg/HttpDxe/HttpImpl.c
@@ -1342,7 +1342,7 @@ HttpResponseWorker (
     // We receive part of header of next HTTP msg.
     //
     if (HttpInstance->NextMsg != NULL) {
-      HttpMsg->BodyLength = MIN ((UINTN) (HttpInstance->NextMsg - (CHAR8 *) Fragment.Bulk), HttpMsg->BodyLength);
+      HttpMsg->BodyLength = MIN ((UINTN) HttpInstance->NextMsg - (UINTN) Fragment.Bulk, HttpMsg->BodyLength);
       CopyMem (HttpMsg->Body, Fragment.Bulk, HttpMsg->BodyLength);
       
       HttpInstance->CacheLen = Fragment.Len - HttpMsg->BodyLength;
@@ -1360,7 +1360,7 @@ HttpResponseWorker (
         CopyMem (HttpInstance->CacheBody, Fragment.Bulk + HttpMsg->BodyLength, HttpInstance->CacheLen);
         HttpInstance->CacheOffset = 0;
 
-        HttpInstance->NextMsg = HttpInstance->CacheBody + (UINTN) (HttpInstance->NextMsg - (CHAR8 *) (Fragment.Bulk + HttpMsg->BodyLength));
+        HttpInstance->NextMsg = HttpInstance->CacheBody + ((UINTN) HttpInstance->NextMsg - (UINTN) (Fragment.Bulk + HttpMsg->BodyLength));
       }
     } else {
       HttpMsg->BodyLength = MIN (Fragment.Len, (UINT32) HttpMsg->BodyLength);
-- 
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v3 5/6] SecurityPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 [PATCH v3 0/6] Refine type cast for pointer subtraction Hao Wu
                   ` (3 preceding siblings ...)
  2017-02-25  4:05 ` [PATCH v3 4/6] NetworkPkg: " Hao Wu
@ 2017-02-25  4:05 ` Hao Wu
  2017-03-06  1:29   ` Zhang, Chao B
  2017-02-25  4:05 ` [PATCH v3 6/6] ShellPkg: " Hao Wu
  5 siblings, 1 reply; 18+ messages in thread
From: Hao Wu @ 2017-02-25  4:05 UTC (permalink / raw)
  To: edk2-devel; +Cc: Hao Wu, Chao Zhang

For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object; the
result is the difference of the subscripts of the two array elements. The
size of the result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
is not representable in an object of that type, the behavior is
undefined."

In our codes, there are cases that the pointer subtraction is not
performed by pointers to elements of the same array object. This might
lead to potential issues, since the behavior is undefined according to C11
standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some
static code checkers may warn that the pointer subtraction might underflow
first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each
pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Chao Zhang <chao.b.zhang@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c        | 16 ++++++++--------
 SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c              | 10 +++++-----
 SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c                                |  6 +++---
 SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c                                  | 10 +++++-----
 SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c                                  | 10 +++++-----
 SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c | 12 ++++++------
 6 files changed, 32 insertions(+), 32 deletions(-)

diff --git a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
index e28e106..588072c 100644
--- a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
+++ b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
@@ -391,13 +391,13 @@ HashPeImage (
     //
     // Use PE32 offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase;
     NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
   } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
     //
     // Use PE32+ offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase;
     NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
   } else {
     //
@@ -425,13 +425,13 @@ HashPeImage (
       // Use PE32 offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
     } else {
       //
       // Use PE32+ offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
     }
 
     if (HashSize != 0) {
@@ -449,13 +449,13 @@ HashPeImage (
       // Use PE32 offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
@@ -474,13 +474,13 @@ HashPeImage (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
     } else {
       //
       // Use PE32+ offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) HashBase - (UINTN) mImageBase);
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c b/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c
index 52bf582..8167a21 100644
--- a/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c
+++ b/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c
@@ -15,7 +15,7 @@
   TcgMeasureGptTable() function will receive untrusted GPT partition table, and parse
   partition data carefully.
 
-Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials 
 are licensed and made available under the terms and conditions of the BSD License 
 which accompanies this distribution.  The full text of the license may be found at 
@@ -443,13 +443,13 @@ TcgMeasurePeImage (
     // Use PE32 offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase;
   } else {
     //
     // Use PE32+ offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase;
   }
 
   HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize);
@@ -494,13 +494,13 @@ TcgMeasurePeImage (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset
       //    
       HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c b/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c
index 64d3c53..180f360 100644
--- a/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c
+++ b/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c
@@ -1,7 +1,7 @@
 /** @file
   Implement TPM2 help.
 
-Copyright (c) 2013 - 2016, Intel Corporation. All rights reserved. <BR>
+Copyright (c) 2013 - 2017, Intel Corporation. All rights reserved. <BR>
 This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
@@ -141,7 +141,7 @@ CopyAuthSessionCommand (
     Buffer += sizeof(UINT16);
   }
 
-  return (UINT32)(UINTN)(Buffer - (UINT8 *)AuthSessionOut);
+  return (UINT32)((UINTN)Buffer - (UINTN)AuthSessionOut);
 }
 
 /**
@@ -186,7 +186,7 @@ CopyAuthSessionResponse (
   CopyMem (AuthSessionOut->hmac.buffer, Buffer, AuthSessionOut->hmac.size);
   Buffer += AuthSessionOut->hmac.size;
 
-  return (UINT32)(UINTN)(Buffer - (UINT8 *)AuthSessionIn);
+  return (UINT32)((UINTN)Buffer - (UINTN)AuthSessionIn);
 }
 
 /**
diff --git a/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c b/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c
index de55ed9..8ee34a7 100644
--- a/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c
+++ b/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c
@@ -6,7 +6,7 @@
   This external input must be validated carefully to avoid security issue like
   buffer overflow, integer overflow.
 
-Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials 
 are licensed and made available under the terms and conditions of the BSD License 
 which accompanies this distribution.  The full text of the license may be found at 
@@ -206,13 +206,13 @@ MeasurePeImageAndExtend (
     // Use PE32 offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase;
   } else {
     //
     // Use PE32+ offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase;
   }
 
   Status = HashUpdate (HashHandle, HashBase, HashSize);
@@ -257,13 +257,13 @@ MeasurePeImageAndExtend (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset
       //    
       HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c b/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c
index b20fc70..a7de588 100644
--- a/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c
+++ b/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c
@@ -6,7 +6,7 @@
   This external input must be validated carefully to avoid security issue like
   buffer overflow, integer overflow.
 
-Copyright (c) 2013 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2013 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials 
 are licensed and made available under the terms and conditions of the BSD License 
 which accompanies this distribution.  The full text of the license may be found at 
@@ -206,13 +206,13 @@ MeasurePeImageAndExtend (
     // Use PE32 offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase;
   } else {
     //
     // Use PE32+ offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase;
   }
 
   Status = HashUpdate (HashHandle, HashBase, HashSize);
@@ -257,13 +257,13 @@ MeasurePeImageAndExtend (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset
       //    
       HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
index 6f58729..52804dd 100644
--- a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
+++ b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
@@ -1837,12 +1837,12 @@ HashPeImage (
     //
     // Use PE32 offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - (UINTN) HashBase;
   } else {
     //
     // Use PE32+ offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - (UINTN) HashBase;
   }
 
   Status  = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
@@ -1859,13 +1859,13 @@ HashPeImage (
     // Use PE32 offset.
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
   } else {
     //
     // Use PE32+ offset.
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - (UINTN) HashBase;
   }
 
   Status  = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
@@ -1881,13 +1881,13 @@ HashPeImage (
     // Use PE32 offset
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-    HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - mImageBase);
+    HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - (UINTN) mImageBase);
   } else {
     //
     // Use PE32+ offset.
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-    HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - mImageBase);
+    HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - ((UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - (UINTN) mImageBase);
   }
 
   Status  = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
-- 
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 [PATCH v3 0/6] Refine type cast for pointer subtraction Hao Wu
                   ` (4 preceding siblings ...)
  2017-02-25  4:05 ` [PATCH v3 5/6] SecurityPkg: " Hao Wu
@ 2017-02-25  4:05 ` Hao Wu
  2017-02-27  5:10   ` Ni, Ruiyu
                     ` (2 more replies)
  5 siblings, 3 replies; 18+ messages in thread
From: Hao Wu @ 2017-02-25  4:05 UTC (permalink / raw)
  To: edk2-devel; +Cc: Hao Wu, Jaben Carsey, Ruiyu Ni

For pointer subtraction, the result is of type "ptrdiff_t". According to
the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the
same array object, or one past the last element of the array object; the
result is the difference of the subscripts of the two array elements. The
size of the result is implementation-defined, and its type (a signed
integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
is not representable in an object of that type, the behavior is
undefined."

In our codes, there are cases that the pointer subtraction is not
performed by pointers to elements of the same array object. This might
lead to potential issues, since the behavior is undefined according to C11
standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some
static code checkers may warn that the pointer subtraction might underflow
first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each
pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Jaben Carsey <jaben.carsey@intel.com>
Cc: Ruiyu Ni <ruiyu.ni@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 ShellPkg/Application/Shell/ShellParametersProtocol.c                | 6 +++---
 ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c              | 4 ++--
 ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c | 4 ++--
 ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c                   | 4 ++--
 ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c                    | 4 ++--
 5 files changed, 11 insertions(+), 11 deletions(-)

diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c b/ShellPkg/Application/Shell/ShellParametersProtocol.c
index 4999155..8d76fb4 100644
--- a/ShellPkg/Application/Shell/ShellParametersProtocol.c
+++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c
@@ -5,7 +5,7 @@
   (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
   Copyright (C) 2014, Red Hat, Inc.
   (C) Copyright 2013 Hewlett-Packard Development Company, L.P.<BR>
-  Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
   This program and the accompanying materials
   are licensed and made available under the terms and conditions of the BSD License
   which accompanies this distribution.  The full text of the license may be found at
@@ -1034,9 +1034,9 @@ UpdateStdInStdOutStdErr(
   StrnCpyS(CommandLineCopy, StrSize(CommandLineCopy)/sizeof(CHAR16), NewCommandLine, StrLen(NewCommandLine));
 
   if (FirstLocation != CommandLineCopy + StrLen(CommandLineCopy)
-    && ((UINTN)(FirstLocation - CommandLineCopy) < StrLen(NewCommandLine))
+    && (((UINTN)FirstLocation - (UINTN)CommandLineCopy)/sizeof(CHAR16) < StrLen(NewCommandLine))
     ){
-    *(NewCommandLine + (UINTN)(FirstLocation - CommandLineCopy)) = CHAR_NULL;
+    *(NewCommandLine + ((UINTN)FirstLocation - (UINTN)CommandLineCopy)/sizeof(CHAR16)) = CHAR_NULL;
   }
 
   if (!EFI_ERROR(Status)) {
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
index bb2c0b9..18f15fa 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
@@ -2,7 +2,7 @@
   Main file for DmpStore shell Debug1 function.
    
   (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.<BR>
-  Copyright (c) 2005 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
   This program and the accompanying materials
   are licensed and made available under the terms and conditions of the BSD License
   which accompanies this distribution.  The full text of the license may be found at
@@ -364,7 +364,7 @@ AppendSingleVariableToFile (
   //
   // Crc32
   //
-  gBS->CalculateCrc32 (Buffer, (UINTN) (Ptr - Buffer), (UINT32 *) Ptr);
+  gBS->CalculateCrc32 (Buffer, (UINTN) Ptr - (UINTN) Buffer, (UINT32 *) Ptr);
 
   Status = ShellWriteFile (FileHandle, &BufferSize, Buffer);
   FreePool (Buffer);
diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
index 56b682a..a5b16fe 100644
--- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
+++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
@@ -2,7 +2,7 @@
   Tools of clarify the content of the smbios table.
 
   (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
-  Copyright (c) 2005 - 2012, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
   This program and the accompanying materials
   are licensed and made available under the terms and conditions of the BSD License
   which accompanies this distribution.  The full text of the license may be found at
@@ -700,7 +700,7 @@ CalculateSmbios64BitStructureCountAndLength (
     //
     // Length = Next structure head - this structure head
     //
-    (*Smbios64TableLength) += (UINTN) (Smbios.Raw - Raw);
+    (*Smbios64TableLength) += ((UINTN) Smbios.Raw - (UINTN) Raw);
     if ((*Smbios64TableLength) > Smbios64EntryPoint->TableMaximumSize) {
     	//
     	// The actual table length exceeds maximum table size,
diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
index d17a29d..0bcee92 100644
--- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
+++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
@@ -75,7 +75,7 @@ IsValidGuidString(
        ) {
       Walker++;
     } else {
-      if (*Walker == L'-' && (UINTN)(Walker - PrevWalker) == mGuidDataLen[Index]) {
+      if (*Walker == L'-' && (((UINTN)Walker - (UINTN)PrevWalker) / sizeof (CHAR16)) == mGuidDataLen[Index]) {
         Walker++;
         PrevWalker = Walker;
         Index++;
@@ -85,7 +85,7 @@ IsValidGuidString(
     }
   }
 
-  if ((UINTN)(Walker - PrevWalker) == mGuidDataLen[Index]) {
+  if ((((UINTN)Walker - (UINTN)PrevWalker) / sizeof (CHAR16)) == mGuidDataLen[Index]) {
     return TRUE;
   } else {
     return FALSE;
diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
index dd4a740..9ae8176 100644
--- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
+++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
@@ -99,10 +99,10 @@ IsCurrentFileSystem (
 
   Splitter2 = StrStr (Cwd, L":");
 
-  if ((UINTN) (Splitter1 - FullPath) != (UINTN) (Splitter2 - Cwd)) {
+  if (((UINTN) Splitter1 - (UINTN) FullPath) != ((UINTN) Splitter2 - (UINTN) Cwd)) {
     return FALSE;
   } else {
-    if (StrniCmp (FullPath, Cwd, (UINTN) (Splitter1 - FullPath)) == NULL) {
+    if (StrniCmp (FullPath, Cwd, ((UINTN) Splitter1 - (UINTN) FullPath) / sizeof (CHAR16)) == NULL) {
       return TRUE;
     } else {
       return FALSE;
-- 
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 2/6] CryptoPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 2/6] CryptoPkg: " Hao Wu
@ 2017-02-27  2:23   ` Long, Qin
  0 siblings, 0 replies; 18+ messages in thread
From: Long, Qin @ 2017-02-27  2:23 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Wu, Hao A, Ye, Ting

Reviewed-by: Qin Long <qin.long@intel.com>


> -----Original Message-----
> From: edk2-devel [mailto:edk2-devel-bounces@lists.01.org] On Behalf Of
> Hao Wu
> Sent: Saturday, February 25, 2017 12:05 PM
> To: edk2-devel@lists.01.org
> Cc: Wu, Hao A; Ye, Ting; Long, Qin
> Subject: [edk2] [PATCH v3 2/6] CryptoPkg: Refine type cast for pointer
> subtraction
> 
> For pointer subtraction, the result is of type "ptrdiff_t". According to the C11
> standard (Committee Draft - April 12, 2011):
> 
> "When two pointers are subtracted, both shall point to elements of the same
> array object, or one past the last element of the array object; the result is the
> difference of the subscripts of the two array elements. The size of the result
> is implementation-defined, and its type (a signed integer type) is ptrdiff_t
> defined in the <stddef.h> header. If the result is not representable in an
> object of that type, the behavior is undefined."
> 
> In our codes, there are cases that the pointer subtraction is not performed
> by pointers to elements of the same array object. This might lead to potential
> issues, since the behavior is undefined according to C11 standard.
> 
> Also, since the size of type "ptrdiff_t" is implementation-defined. Some
> static code checkers may warn that the pointer subtraction might underflow
> first and then being cast to a bigger size. For example:
> 
> UINT8  *Ptr1, *Ptr2;
> UINTN  PtrDiff;
> ...
> PtrDiff = (UINTN) (Ptr1 - Ptr2);
> 
> The commit will refine the pointer subtraction expressions by casting each
> pointer to UINTN first and then perform the subtraction:
> 
> PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;
> 
> Cc: Qin Long <qin.long@intel.com>
> Cc: Ting Ye <ting.ye@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Hao Wu <hao.a.wu@intel.com>
> Acked-by: Laszlo Ersek <lersek@redhat.com>
> ---
>  CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c | 6 +++---
>  1 file changed, 3 insertions(+), 3 deletions(-)
> 
> diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c
> b/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c
> index 19c30dc..feaa371 100644
> --- a/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c
> +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/RuntimeMemAllocation.c
> @@ -2,7 +2,7 @@
>    Light-weight Memory Management Routines for OpenSSL-based Crypto
>    Library at Runtime Phase.
> 
> -Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
> +Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
>  This program and the accompanying materials  are licensed and made
> available under the terms and conditions of the BSD License  which
> accompanies this distribution.  The full text of the license may be found at
> @@ -282,7 +282,7 @@ RuntimeFreeMem (
>    UINTN  StartOffset;
>    UINTN  StartPageIndex;
> 
> -  StartOffset    = (UINTN) ((UINT8 *)Buffer - mRTPageTable->DataAreaBase);
> +  StartOffset    = (UINTN)Buffer - (UINTN)mRTPageTable->DataAreaBase;
>    StartPageIndex = RT_SIZE_TO_PAGES (mRTPageTable-
> >Pages[RT_SIZE_TO_PAGES(StartOffset)].StartPageOffset);
> 
>    while (StartPageIndex < mRTPageTable->PageCount) { @@ -403,7 +403,7
> @@ void *realloc (void *ptr, size_t size)
>    //
>    // Get Original Size of ptr
>    //
> -  StartOffset    = (UINTN) ((UINT8 *)ptr - mRTPageTable->DataAreaBase);
> +  StartOffset    = (UINTN)ptr - (UINTN)mRTPageTable->DataAreaBase;
>    StartPageIndex = RT_SIZE_TO_PAGES (mRTPageTable-
> >Pages[RT_SIZE_TO_PAGES (StartOffset)].StartPageOffset);
>    PageCount      = 0;
>    while (StartPageIndex < mRTPageTable->PageCount) {
> --
> 1.9.5.msysgit.0
> 
> _______________________________________________
> edk2-devel mailing list
> edk2-devel@lists.01.org
> https://lists.01.org/mailman/listinfo/edk2-devel


^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 6/6] ShellPkg: " Hao Wu
@ 2017-02-27  5:10   ` Ni, Ruiyu
  2017-02-27  5:59     ` Wu, Hao A
  2017-02-27  7:18   ` Ni, Ruiyu
  2017-02-27 16:38   ` Carsey, Jaben
  2 siblings, 1 reply; 18+ messages in thread
From: Ni, Ruiyu @ 2017-02-27  5:10 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Carsey, Jaben



Thanks/Ray

> -----Original Message-----
> From: Wu, Hao A
> Sent: Saturday, February 25, 2017 12:05 PM
> To: edk2-devel@lists.01.org
> Cc: Wu, Hao A <hao.a.wu@intel.com>; Carsey, Jaben
> <jaben.carsey@intel.com>; Ni, Ruiyu <ruiyu.ni@intel.com>
> Subject: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
> 
> For pointer subtraction, the result is of type "ptrdiff_t". According to
> the C11 standard (Committee Draft - April 12, 2011):
> 
> "When two pointers are subtracted, both shall point to elements of the
> same array object, or one past the last element of the array object; the
> result is the difference of the subscripts of the two array elements. The
> size of the result is implementation-defined, and its type (a signed
> integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
> is not representable in an object of that type, the behavior is
> undefined."
> 
> In our codes, there are cases that the pointer subtraction is not
> performed by pointers to elements of the same array object. This might
> lead to potential issues, since the behavior is undefined according to C11
> standard.
> 
> Also, since the size of type "ptrdiff_t" is implementation-defined. Some
> static code checkers may warn that the pointer subtraction might underflow
> first and then being cast to a bigger size. For example:
> 
> UINT8  *Ptr1, *Ptr2;
> UINTN  PtrDiff;
> ...
> PtrDiff = (UINTN) (Ptr1 - Ptr2);
> 
> The commit will refine the pointer subtraction expressions by casting each
> pointer to UINTN first and then perform the subtraction:
> 
> PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Is this the new coding rule? I think the below code is not very readable:
Diff = ((UINTN) Ptr1 - (UINTN) Ptr2) / sizeof (STRUCTURE))
Do we have better fix?

> 
> Cc: Jaben Carsey <jaben.carsey@intel.com>
> Cc: Ruiyu Ni <ruiyu.ni@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Hao Wu <hao.a.wu@intel.com>
> Acked-by: Laszlo Ersek <lersek@redhat.com>
> ---
>  ShellPkg/Application/Shell/ShellParametersProtocol.c                | 6 +++---
>  ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c              | 4 ++--
>  ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
> | 4 ++--
>  ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c                   | 4 ++--
>  ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c                    | 4 ++--
>  5 files changed, 11 insertions(+), 11 deletions(-)
> 
> diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> index 4999155..8d76fb4 100644
> --- a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> +++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> @@ -5,7 +5,7 @@
>    (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
>    Copyright (C) 2014, Red Hat, Inc.
>    (C) Copyright 2013 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -1034,9 +1034,9 @@ UpdateStdInStdOutStdErr(
>    StrnCpyS(CommandLineCopy, StrSize(CommandLineCopy)/sizeof(CHAR16),
> NewCommandLine, StrLen(NewCommandLine));
> 
>    if (FirstLocation != CommandLineCopy + StrLen(CommandLineCopy)
> -    && ((UINTN)(FirstLocation - CommandLineCopy) <
> StrLen(NewCommandLine))
> +    && (((UINTN)FirstLocation - (UINTN)CommandLineCopy)/sizeof(CHAR16)
> < StrLen(NewCommandLine))
>      ){
> -    *(NewCommandLine + (UINTN)(FirstLocation - CommandLineCopy)) =
> CHAR_NULL;
> +    *(NewCommandLine + ((UINTN)FirstLocation -
> (UINTN)CommandLineCopy)/sizeof(CHAR16)) = CHAR_NULL;
>    }
> 
>    if (!EFI_ERROR(Status)) {
> diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> index bb2c0b9..18f15fa 100644
> --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> @@ -2,7 +2,7 @@
>    Main file for DmpStore shell Debug1 function.
> 
>    (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2005 - 2016, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -364,7 +364,7 @@ AppendSingleVariableToFile (
>    //
>    // Crc32
>    //
> -  gBS->CalculateCrc32 (Buffer, (UINTN) (Ptr - Buffer), (UINT32 *) Ptr);
> +  gBS->CalculateCrc32 (Buffer, (UINTN) Ptr - (UINTN) Buffer, (UINT32 *) Ptr);
> 
>    Status = ShellWriteFile (FileHandle, &BufferSize, Buffer);
>    FreePool (Buffer);
> diff --git
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> index 56b682a..a5b16fe 100644
> ---
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> +++
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> @@ -2,7 +2,7 @@
>    Tools of clarify the content of the smbios table.
> 
>    (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2005 - 2012, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -700,7 +700,7 @@ CalculateSmbios64BitStructureCountAndLength (
>      //
>      // Length = Next structure head - this structure head
>      //
> -    (*Smbios64TableLength) += (UINTN) (Smbios.Raw - Raw);
> +    (*Smbios64TableLength) += ((UINTN) Smbios.Raw - (UINTN) Raw);
>      if ((*Smbios64TableLength) > Smbios64EntryPoint->TableMaximumSize) {
>      	//
>      	// The actual table length exceeds maximum table size,
> diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> index d17a29d..0bcee92 100644
> --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> @@ -75,7 +75,7 @@ IsValidGuidString(
>         ) {
>        Walker++;
>      } else {
> -      if (*Walker == L'-' && (UINTN)(Walker - PrevWalker) ==
> mGuidDataLen[Index]) {
> +      if (*Walker == L'-' && (((UINTN)Walker - (UINTN)PrevWalker) / sizeof
> (CHAR16)) == mGuidDataLen[Index]) {
>          Walker++;
>          PrevWalker = Walker;
>          Index++;
> @@ -85,7 +85,7 @@ IsValidGuidString(
>      }
>    }
> 
> -  if ((UINTN)(Walker - PrevWalker) == mGuidDataLen[Index]) {
> +  if ((((UINTN)Walker - (UINTN)PrevWalker) / sizeof (CHAR16)) ==
> mGuidDataLen[Index]) {
>      return TRUE;
>    } else {
>      return FALSE;
> diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> index dd4a740..9ae8176 100644
> --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> @@ -99,10 +99,10 @@ IsCurrentFileSystem (
> 
>    Splitter2 = StrStr (Cwd, L":");
> 
> -  if ((UINTN) (Splitter1 - FullPath) != (UINTN) (Splitter2 - Cwd)) {
> +  if (((UINTN) Splitter1 - (UINTN) FullPath) != ((UINTN) Splitter2 - (UINTN)
> Cwd)) {
>      return FALSE;
>    } else {
> -    if (StrniCmp (FullPath, Cwd, (UINTN) (Splitter1 - FullPath)) == NULL) {
> +    if (StrniCmp (FullPath, Cwd, ((UINTN) Splitter1 - (UINTN) FullPath) / sizeof
> (CHAR16)) == NULL) {
>        return TRUE;
>      } else {
>        return FALSE;
> --
> 1.9.5.msysgit.0



^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
  2017-02-27  5:10   ` Ni, Ruiyu
@ 2017-02-27  5:59     ` Wu, Hao A
  2017-02-27  7:06       ` Ni, Ruiyu
  0 siblings, 1 reply; 18+ messages in thread
From: Wu, Hao A @ 2017-02-27  5:59 UTC (permalink / raw)
  To: Ni, Ruiyu, edk2-devel@lists.01.org; +Cc: Carsey, Jaben

> -----Original Message-----
> From: Ni, Ruiyu
> Sent: Monday, February 27, 2017 1:10 PM
> To: Wu, Hao A; edk2-devel@lists.01.org
> Cc: Carsey, Jaben
> Subject: RE: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
> 
> 
> 
> Thanks/Ray
> 
> > -----Original Message-----
> > From: Wu, Hao A
> > Sent: Saturday, February 25, 2017 12:05 PM
> > To: edk2-devel@lists.01.org
> > Cc: Wu, Hao A <hao.a.wu@intel.com>; Carsey, Jaben
> > <jaben.carsey@intel.com>; Ni, Ruiyu <ruiyu.ni@intel.com>
> > Subject: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
> >
> > For pointer subtraction, the result is of type "ptrdiff_t". According to
> > the C11 standard (Committee Draft - April 12, 2011):
> >
> > "When two pointers are subtracted, both shall point to elements of the
> > same array object, or one past the last element of the array object; the
> > result is the difference of the subscripts of the two array elements. The
> > size of the result is implementation-defined, and its type (a signed
> > integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
> > is not representable in an object of that type, the behavior is
> > undefined."
> >
> > In our codes, there are cases that the pointer subtraction is not
> > performed by pointers to elements of the same array object. This might
> > lead to potential issues, since the behavior is undefined according to C11
> > standard.
> >
> > Also, since the size of type "ptrdiff_t" is implementation-defined. Some
> > static code checkers may warn that the pointer subtraction might underflow
> > first and then being cast to a bigger size. For example:
> >
> > UINT8  *Ptr1, *Ptr2;
> > UINTN  PtrDiff;
> > ...
> > PtrDiff = (UINTN) (Ptr1 - Ptr2);
> >
> > The commit will refine the pointer subtraction expressions by casting each
> > pointer to UINTN first and then perform the subtraction:
> >
> > PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;
> 
> Is this the new coding rule? I think the below code is not very readable:
> Diff = ((UINTN) Ptr1 - (UINTN) Ptr2) / sizeof (STRUCTURE))
> Do we have better fix?
> 

Hi Ray,

Most of the pointer subtraction expressions in the code base are not
performed between two pointers to elements of the same array object, or
one past the last element of the array object (according to C11 standard).
Although the refined code is less readable, but I think the refine stick
with the standard better.

The number of pointer subtractions used in the edk2 code base is not
very large. So the series does not touch lots of files. Also, we may take
this as part of the coding style when dealing with pointer subtractions.

Best Regards,
Hao Wu

> >
> > Cc: Jaben Carsey <jaben.carsey@intel.com>
> > Cc: Ruiyu Ni <ruiyu.ni@intel.com>
> > Contributed-under: TianoCore Contribution Agreement 1.0
> > Signed-off-by: Hao Wu <hao.a.wu@intel.com>
> > Acked-by: Laszlo Ersek <lersek@redhat.com>
> > ---
> >  ShellPkg/Application/Shell/ShellParametersProtocol.c                | 6 +++---
> >  ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c              | 4 ++--
> >  ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
> > | 4 ++--
> >  ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c                   | 4 ++--
> >  ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c                    | 4 ++--
> >  5 files changed, 11 insertions(+), 11 deletions(-)
> >
> > diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > index 4999155..8d76fb4 100644
> > --- a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > +++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > @@ -5,7 +5,7 @@
> >    (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
> >    Copyright (C) 2014, Red Hat, Inc.
> >    (C) Copyright 2013 Hewlett-Packard Development Company, L.P.<BR>
> > -  Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
> > +  Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
> >    This program and the accompanying materials
> >    are licensed and made available under the terms and conditions of the BSD
> > License
> >    which accompanies this distribution.  The full text of the license may be
> > found at
> > @@ -1034,9 +1034,9 @@ UpdateStdInStdOutStdErr(
> >    StrnCpyS(CommandLineCopy, StrSize(CommandLineCopy)/sizeof(CHAR16),
> > NewCommandLine, StrLen(NewCommandLine));
> >
> >    if (FirstLocation != CommandLineCopy + StrLen(CommandLineCopy)
> > -    && ((UINTN)(FirstLocation - CommandLineCopy) <
> > StrLen(NewCommandLine))
> > +    && (((UINTN)FirstLocation - (UINTN)CommandLineCopy)/sizeof(CHAR16)
> > < StrLen(NewCommandLine))
> >      ){
> > -    *(NewCommandLine + (UINTN)(FirstLocation - CommandLineCopy)) =
> > CHAR_NULL;
> > +    *(NewCommandLine + ((UINTN)FirstLocation -
> > (UINTN)CommandLineCopy)/sizeof(CHAR16)) = CHAR_NULL;
> >    }
> >
> >    if (!EFI_ERROR(Status)) {
> > diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > index bb2c0b9..18f15fa 100644
> > --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > @@ -2,7 +2,7 @@
> >    Main file for DmpStore shell Debug1 function.
> >
> >    (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.<BR>
> > -  Copyright (c) 2005 - 2016, Intel Corporation. All rights reserved.<BR>
> > +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
> >    This program and the accompanying materials
> >    are licensed and made available under the terms and conditions of the BSD
> > License
> >    which accompanies this distribution.  The full text of the license may be
> > found at
> > @@ -364,7 +364,7 @@ AppendSingleVariableToFile (
> >    //
> >    // Crc32
> >    //
> > -  gBS->CalculateCrc32 (Buffer, (UINTN) (Ptr - Buffer), (UINT32 *) Ptr);
> > +  gBS->CalculateCrc32 (Buffer, (UINTN) Ptr - (UINTN) Buffer, (UINT32 *) Ptr);
> >
> >    Status = ShellWriteFile (FileHandle, &BufferSize, Buffer);
> >    FreePool (Buffer);
> > diff --git
> > a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > .c
> > b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > .c
> > index 56b682a..a5b16fe 100644
> > ---
> > a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > .c
> > +++
> > b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > .c
> > @@ -2,7 +2,7 @@
> >    Tools of clarify the content of the smbios table.
> >
> >    (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
> > -  Copyright (c) 2005 - 2012, Intel Corporation. All rights reserved.<BR>
> > +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
> >    This program and the accompanying materials
> >    are licensed and made available under the terms and conditions of the BSD
> > License
> >    which accompanies this distribution.  The full text of the license may be
> > found at
> > @@ -700,7 +700,7 @@ CalculateSmbios64BitStructureCountAndLength (
> >      //
> >      // Length = Next structure head - this structure head
> >      //
> > -    (*Smbios64TableLength) += (UINTN) (Smbios.Raw - Raw);
> > +    (*Smbios64TableLength) += ((UINTN) Smbios.Raw - (UINTN) Raw);
> >      if ((*Smbios64TableLength) > Smbios64EntryPoint->TableMaximumSize) {
> >      	//
> >      	// The actual table length exceeds maximum table size,
> > diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > index d17a29d..0bcee92 100644
> > --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > @@ -75,7 +75,7 @@ IsValidGuidString(
> >         ) {
> >        Walker++;
> >      } else {
> > -      if (*Walker == L'-' && (UINTN)(Walker - PrevWalker) ==
> > mGuidDataLen[Index]) {
> > +      if (*Walker == L'-' && (((UINTN)Walker - (UINTN)PrevWalker) / sizeof
> > (CHAR16)) == mGuidDataLen[Index]) {
> >          Walker++;
> >          PrevWalker = Walker;
> >          Index++;
> > @@ -85,7 +85,7 @@ IsValidGuidString(
> >      }
> >    }
> >
> > -  if ((UINTN)(Walker - PrevWalker) == mGuidDataLen[Index]) {
> > +  if ((((UINTN)Walker - (UINTN)PrevWalker) / sizeof (CHAR16)) ==
> > mGuidDataLen[Index]) {
> >      return TRUE;
> >    } else {
> >      return FALSE;
> > diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > index dd4a740..9ae8176 100644
> > --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > @@ -99,10 +99,10 @@ IsCurrentFileSystem (
> >
> >    Splitter2 = StrStr (Cwd, L":");
> >
> > -  if ((UINTN) (Splitter1 - FullPath) != (UINTN) (Splitter2 - Cwd)) {
> > +  if (((UINTN) Splitter1 - (UINTN) FullPath) != ((UINTN) Splitter2 - (UINTN)
> > Cwd)) {
> >      return FALSE;
> >    } else {
> > -    if (StrniCmp (FullPath, Cwd, (UINTN) (Splitter1 - FullPath)) == NULL) {
> > +    if (StrniCmp (FullPath, Cwd, ((UINTN) Splitter1 - (UINTN) FullPath) / sizeof
> > (CHAR16)) == NULL) {
> >        return TRUE;
> >      } else {
> >        return FALSE;
> > --
> > 1.9.5.msysgit.0



^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 3/6] IntelFrameworkModulePkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 3/6] IntelFrameworkModulePkg: " Hao Wu
@ 2017-02-27  6:59   ` Fan, Jeff
  0 siblings, 0 replies; 18+ messages in thread
From: Fan, Jeff @ 2017-02-27  6:59 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org

Reviewed-by: Jeff Fan <jeff.fan@intel.com>

-----Original Message-----
From: Wu, Hao A 
Sent: Saturday, February 25, 2017 12:05 PM
To: edk2-devel@lists.01.org
Cc: Wu, Hao A; Fan, Jeff
Subject: [PATCH v3 3/6] IntelFrameworkModulePkg: Refine type cast for pointer subtraction

For pointer subtraction, the result is of type "ptrdiff_t". According to the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined."

In our codes, there are cases that the pointer subtraction is not performed by pointers to elements of the same array object. This might lead to potential issues, since the behavior is undefined according to C11 standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some static code checkers may warn that the pointer subtraction might underflow first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Jeff Fan <jeff.fan@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c           | 4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c         | 4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c      | 4 ++--
 IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c         | 4 ++--
 IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c | 4 ++--  IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c | 6 +++---
 6 files changed, 13 insertions(+), 13 deletions(-)

diff --git a/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c b/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
index 8f91a7d..c4c77ec 100644
--- a/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
+++ b/IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
@@ -1,6 +1,6 @@
 /** @file
 
-Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 
 This program and the accompanying materials  are licensed and made available under the terms and conditions @@ -318,7 +318,7 @@ GetPciLegacyRom (
       break;
     }
 
-    if ((UINTN)(RomHeader.Raw - (UINT8 *) *Rom) + Pcir->ImageLength * 512 > *ImageSize) {
+    if (((UINTN)RomHeader.Raw - (UINTN)*Rom) + Pcir->ImageLength * 512 
+ > *ImageSize) {
       break;
     }
     
diff --git a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
index bba62a8..628424d 100644
--- a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
+++ b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsBoot.c
@@ -1,7 +1,7 @@
 /** @file
   BDS Lib functions which relate with create or process the boot option.
 
-Copyright (c) 2004 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -1034,7 +1034,7 @@ BdsCreateDevOrder (
   DevOrderPtr->Length  = (UINT16) (sizeof (UINT16) + BEVCount * sizeof (UINT16));
   DevOrderPtr          = (LEGACY_DEV_ORDER_ENTRY *) BdsFillDevOrderBuf (BbsTable, BBS_BEV_DEVICE, BbsCount, DevOrderPtr->Data);
 
-  ASSERT (TotalSize == (UINTN) ((UINT8 *) DevOrderPtr - (UINT8 *) DevOrder));
+  ASSERT (TotalSize == ((UINTN) DevOrderPtr - (UINTN) DevOrder));
 
   //
   // Save device order for legacy boot device to variable.
diff --git a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c
index 1020e84..8f273ff 100644
--- a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c
+++ b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsConsole.c
@@ -1,7 +1,7 @@
 /** @file
   BDS Lib functions which contain all the code to connect console device
 
-Copyright (c) 2004 - 2014, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -873,7 +873,7 @@ ConvertBmpToGopBlt (
 
     }
 
-    ImageIndex = (UINTN) (Image - ImageHeader);
+    ImageIndex = (UINTN)Image - (UINTN)ImageHeader;
     if ((ImageIndex % 4) != 0) {
       //
       // Bmp Image starts each row on a 32-bit boundary!
diff --git a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c
index 24c1998..2ba511a 100644
--- a/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c
+++ b/IntelFrameworkModulePkg/Library/GenericBdsLib/BdsMisc.c
@@ -1,7 +1,7 @@
 /** @file
   Misc BDS library function
 
-Copyright (c) 2004 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -669,7 +669,7 @@ BdsLibVariableToOption (
   // Get load opion data.
   //
   LoadOptions     = TempPtr;
-  LoadOptionsSize = (UINT32) (VariableSize - (UINTN) (TempPtr - Variable));
+  LoadOptionsSize = (UINT32) (VariableSize - ((UINTN)TempPtr - 
+ (UINTN)Variable));
 
   //
   // The Console variables may have multiple device paths, so make diff --git a/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c b/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c
index c56a878..080a436 100644
--- a/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c
+++ b/IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBm.c
@@ -3,7 +3,7 @@
   and manage the legacy boot option, all legacy boot option is getting from
   the legacy BBS table.
 
-Copyright (c) 2011 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -725,7 +725,7 @@ LegacyBmCreateDevOrder (
   DevOrderPtr->Length  = (UINT16) (sizeof (UINT16) + BEVCount * sizeof (UINT16));
   DevOrderPtr          = (LEGACY_DEV_ORDER_ENTRY *) LegacyBmFillDevOrderBuf (BbsTable, BBS_BEV_DEVICE, BbsCount, DevOrderPtr->Data);
 
-  ASSERT (TotalSize == (UINTN) ((UINT8 *) DevOrderPtr - (UINT8 *) DevOrder));
+  ASSERT (TotalSize == ((UINTN) DevOrderPtr - (UINTN) DevOrder));
 
   //
   // Save device order for legacy boot device to variable.
diff --git a/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c b/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
index 5898fb3..6233a11 100644
--- a/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
+++ b/IntelFrameworkModulePkg/Universal/BdsDxe/BootMaint/BootOption.c
@@ -5,7 +5,7 @@
 
   Boot option manipulation
 
-Copyright (c) 2004 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -1124,7 +1124,7 @@ BOpt_AppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 3);
-      StrCpyS (LastSlash, MaxLen - (UINTN) (LastSlash - Str), TmpStr);
+      StrCpyS (LastSlash, MaxLen - ((UINTN) LastSlash - (UINTN) Str) / 
+ sizeof (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '\\') {
       //
@@ -1136,7 +1136,7 @@ BOpt_AppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 2);
-      StrCpyS (Ptr, MaxLen - (UINTN) (Ptr - Str), TmpStr);
+      StrCpyS (Ptr, MaxLen - ((UINTN) Ptr - (UINTN) Str) / sizeof 
+ (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\') {
       LastSlash = Ptr;
--
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
  2017-02-27  5:59     ` Wu, Hao A
@ 2017-02-27  7:06       ` Ni, Ruiyu
  0 siblings, 0 replies; 18+ messages in thread
From: Ni, Ruiyu @ 2017-02-27  7:06 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Carsey, Jaben



Thanks/Ray

> -----Original Message-----
> From: Wu, Hao A
> Sent: Monday, February 27, 2017 1:59 PM
> To: Ni, Ruiyu <ruiyu.ni@intel.com>; edk2-devel@lists.01.org
> Cc: Carsey, Jaben <jaben.carsey@intel.com>
> Subject: RE: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
> 
> > -----Original Message-----
> > From: Ni, Ruiyu
> > Sent: Monday, February 27, 2017 1:10 PM
> > To: Wu, Hao A; edk2-devel@lists.01.org
> > Cc: Carsey, Jaben
> > Subject: RE: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer
> > subtraction
> >
> >
> >
> > Thanks/Ray
> >
> > > -----Original Message-----
> > > From: Wu, Hao A
> > > Sent: Saturday, February 25, 2017 12:05 PM
> > > To: edk2-devel@lists.01.org
> > > Cc: Wu, Hao A <hao.a.wu@intel.com>; Carsey, Jaben
> > > <jaben.carsey@intel.com>; Ni, Ruiyu <ruiyu.ni@intel.com>
> > > Subject: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer
> > > subtraction
> > >
> > > For pointer subtraction, the result is of type "ptrdiff_t".
> > > According to the C11 standard (Committee Draft - April 12, 2011):
> > >
> > > "When two pointers are subtracted, both shall point to elements of
> > > the same array object, or one past the last element of the array
> > > object; the result is the difference of the subscripts of the two
> > > array elements. The size of the result is implementation-defined,
> > > and its type (a signed integer type) is ptrdiff_t defined in the
> > > <stddef.h> header. If the result is not representable in an object
> > > of that type, the behavior is undefined."
> > >
> > > In our codes, there are cases that the pointer subtraction is not
> > > performed by pointers to elements of the same array object. This
> > > might lead to potential issues, since the behavior is undefined
> > > according to C11 standard.
> > >
> > > Also, since the size of type "ptrdiff_t" is implementation-defined.
> > > Some static code checkers may warn that the pointer subtraction
> > > might underflow first and then being cast to a bigger size. For example:
> > >
> > > UINT8  *Ptr1, *Ptr2;
> > > UINTN  PtrDiff;
> > > ...
> > > PtrDiff = (UINTN) (Ptr1 - Ptr2);
> > >
> > > The commit will refine the pointer subtraction expressions by
> > > casting each pointer to UINTN first and then perform the subtraction:
> > >
> > > PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;
> >
> > Is this the new coding rule? I think the below code is not very readable:
> > Diff = ((UINTN) Ptr1 - (UINTN) Ptr2) / sizeof (STRUCTURE)) Do we have
> > better fix?
> >
> 
> Hi Ray,
> 
> Most of the pointer subtraction expressions in the code base are not
> performed between two pointers to elements of the same array object, or
> one past the last element of the array object (according to C11 standard).
> Although the refined code is less readable, but I think the refine stick with
> the standard better.
> 
> The number of pointer subtractions used in the edk2 code base is not very
> large. So the series does not touch lots of files. Also, we may take this as part
> of the coding style when dealing with pointer subtractions.

Thanks for the explanation. If the number of cases is small, I am fine!

> 
> Best Regards,
> Hao Wu
> 
> > >
> > > Cc: Jaben Carsey <jaben.carsey@intel.com>
> > > Cc: Ruiyu Ni <ruiyu.ni@intel.com>
> > > Contributed-under: TianoCore Contribution Agreement 1.0
> > > Signed-off-by: Hao Wu <hao.a.wu@intel.com>
> > > Acked-by: Laszlo Ersek <lersek@redhat.com>
> > > ---
> > >  ShellPkg/Application/Shell/ShellParametersProtocol.c                | 6 +++---
> > >  ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c              | 4
> ++--
> > >
> ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
> > > | 4 ++--
> > >  ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c                   | 4 ++--
> > >  ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c                    | 4 ++--
> > >  5 files changed, 11 insertions(+), 11 deletions(-)
> > >
> > > diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > > b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > > index 4999155..8d76fb4 100644
> > > --- a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > > +++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> > > @@ -5,7 +5,7 @@
> > >    (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
> > >    Copyright (C) 2014, Red Hat, Inc.
> > >    (C) Copyright 2013 Hewlett-Packard Development Company, L.P.<BR>
> > > -  Copyright (c) 2009 - 2016, Intel Corporation. All rights
> > > reserved.<BR>
> > > +  Copyright (c) 2009 - 2017, Intel Corporation. All rights
> > > + reserved.<BR>
> > >    This program and the accompanying materials
> > >    are licensed and made available under the terms and conditions of
> > > the BSD License
> > >    which accompanies this distribution.  The full text of the
> > > license may be found at @@ -1034,9 +1034,9 @@
> > > UpdateStdInStdOutStdErr(
> > >    StrnCpyS(CommandLineCopy,
> > > StrSize(CommandLineCopy)/sizeof(CHAR16),
> > > NewCommandLine, StrLen(NewCommandLine));
> > >
> > >    if (FirstLocation != CommandLineCopy + StrLen(CommandLineCopy)
> > > -    && ((UINTN)(FirstLocation - CommandLineCopy) <
> > > StrLen(NewCommandLine))
> > > +    && (((UINTN)FirstLocation -
> > > + (UINTN)CommandLineCopy)/sizeof(CHAR16)
> > > < StrLen(NewCommandLine))
> > >      ){
> > > -    *(NewCommandLine + (UINTN)(FirstLocation - CommandLineCopy)) =
> > > CHAR_NULL;
> > > +    *(NewCommandLine + ((UINTN)FirstLocation -
> > > (UINTN)CommandLineCopy)/sizeof(CHAR16)) = CHAR_NULL;
> > >    }
> > >
> > >    if (!EFI_ERROR(Status)) {
> > > diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > > b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > > index bb2c0b9..18f15fa 100644
> > > --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > > +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> > > @@ -2,7 +2,7 @@
> > >    Main file for DmpStore shell Debug1 function.
> > >
> > >    (C) Copyright 2013-2015 Hewlett-Packard Development Company,
> > > L.P.<BR>
> > > -  Copyright (c) 2005 - 2016, Intel Corporation. All rights
> > > reserved.<BR>
> > > +  Copyright (c) 2005 - 2017, Intel Corporation. All rights
> > > + reserved.<BR>
> > >    This program and the accompanying materials
> > >    are licensed and made available under the terms and conditions of
> > > the BSD License
> > >    which accompanies this distribution.  The full text of the
> > > license may be found at @@ -364,7 +364,7 @@
> > > AppendSingleVariableToFile (
> > >    //
> > >    // Crc32
> > >    //
> > > -  gBS->CalculateCrc32 (Buffer, (UINTN) (Ptr - Buffer), (UINT32 *)
> > > Ptr);
> > > +  gBS->CalculateCrc32 (Buffer, (UINTN) Ptr - (UINTN) Buffer,
> > > + (UINT32 *) Ptr);
> > >
> > >    Status = ShellWriteFile (FileHandle, &BufferSize, Buffer);
> > >    FreePool (Buffer);
> > > diff --git
> > >
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > > .c
> > >
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > > .c
> > > index 56b682a..a5b16fe 100644
> > > ---
> > >
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > > .c
> > > +++
> > >
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> > > .c
> > > @@ -2,7 +2,7 @@
> > >    Tools of clarify the content of the smbios table.
> > >
> > >    (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
> > > -  Copyright (c) 2005 - 2012, Intel Corporation. All rights
> > > reserved.<BR>
> > > +  Copyright (c) 2005 - 2017, Intel Corporation. All rights
> > > + reserved.<BR>
> > >    This program and the accompanying materials
> > >    are licensed and made available under the terms and conditions of
> > > the BSD License
> > >    which accompanies this distribution.  The full text of the
> > > license may be found at @@ -700,7 +700,7 @@
> > > CalculateSmbios64BitStructureCountAndLength (
> > >      //
> > >      // Length = Next structure head - this structure head
> > >      //
> > > -    (*Smbios64TableLength) += (UINTN) (Smbios.Raw - Raw);
> > > +    (*Smbios64TableLength) += ((UINTN) Smbios.Raw - (UINTN) Raw);
> > >      if ((*Smbios64TableLength) > Smbios64EntryPoint-
> >TableMaximumSize) {
> > >      	//
> > >      	// The actual table length exceeds maximum table size, diff
> > > --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > > b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > > index d17a29d..0bcee92 100644
> > > --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > > +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> > > @@ -75,7 +75,7 @@ IsValidGuidString(
> > >         ) {
> > >        Walker++;
> > >      } else {
> > > -      if (*Walker == L'-' && (UINTN)(Walker - PrevWalker) ==
> > > mGuidDataLen[Index]) {
> > > +      if (*Walker == L'-' && (((UINTN)Walker - (UINTN)PrevWalker) /
> > > + sizeof
> > > (CHAR16)) == mGuidDataLen[Index]) {
> > >          Walker++;
> > >          PrevWalker = Walker;
> > >          Index++;
> > > @@ -85,7 +85,7 @@ IsValidGuidString(
> > >      }
> > >    }
> > >
> > > -  if ((UINTN)(Walker - PrevWalker) == mGuidDataLen[Index]) {
> > > +  if ((((UINTN)Walker - (UINTN)PrevWalker) / sizeof (CHAR16)) ==
> > > mGuidDataLen[Index]) {
> > >      return TRUE;
> > >    } else {
> > >      return FALSE;
> > > diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > > b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > > index dd4a740..9ae8176 100644
> > > --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > > +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> > > @@ -99,10 +99,10 @@ IsCurrentFileSystem (
> > >
> > >    Splitter2 = StrStr (Cwd, L":");
> > >
> > > -  if ((UINTN) (Splitter1 - FullPath) != (UINTN) (Splitter2 - Cwd))
> > > {
> > > +  if (((UINTN) Splitter1 - (UINTN) FullPath) != ((UINTN) Splitter2
> > > + - (UINTN)
> > > Cwd)) {
> > >      return FALSE;
> > >    } else {
> > > -    if (StrniCmp (FullPath, Cwd, (UINTN) (Splitter1 - FullPath)) == NULL) {
> > > +    if (StrniCmp (FullPath, Cwd, ((UINTN) Splitter1 - (UINTN)
> > > + FullPath) / sizeof
> > > (CHAR16)) == NULL) {
> > >        return TRUE;
> > >      } else {
> > >        return FALSE;
> > > --
> > > 1.9.5.msysgit.0



^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 6/6] ShellPkg: " Hao Wu
  2017-02-27  5:10   ` Ni, Ruiyu
@ 2017-02-27  7:18   ` Ni, Ruiyu
  2017-02-27 16:38   ` Carsey, Jaben
  2 siblings, 0 replies; 18+ messages in thread
From: Ni, Ruiyu @ 2017-02-27  7:18 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Carsey, Jaben

Reviewed-by: Ruiyu Ni <ruiyu.ni@intel.com>

Thanks/Ray

> -----Original Message-----
> From: Wu, Hao A
> Sent: Saturday, February 25, 2017 12:05 PM
> To: edk2-devel@lists.01.org
> Cc: Wu, Hao A <hao.a.wu@intel.com>; Carsey, Jaben
> <jaben.carsey@intel.com>; Ni, Ruiyu <ruiyu.ni@intel.com>
> Subject: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
> 
> For pointer subtraction, the result is of type "ptrdiff_t". According to
> the C11 standard (Committee Draft - April 12, 2011):
> 
> "When two pointers are subtracted, both shall point to elements of the
> same array object, or one past the last element of the array object; the
> result is the difference of the subscripts of the two array elements. The
> size of the result is implementation-defined, and its type (a signed
> integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
> is not representable in an object of that type, the behavior is
> undefined."
> 
> In our codes, there are cases that the pointer subtraction is not
> performed by pointers to elements of the same array object. This might
> lead to potential issues, since the behavior is undefined according to C11
> standard.
> 
> Also, since the size of type "ptrdiff_t" is implementation-defined. Some
> static code checkers may warn that the pointer subtraction might underflow
> first and then being cast to a bigger size. For example:
> 
> UINT8  *Ptr1, *Ptr2;
> UINTN  PtrDiff;
> ...
> PtrDiff = (UINTN) (Ptr1 - Ptr2);
> 
> The commit will refine the pointer subtraction expressions by casting each
> pointer to UINTN first and then perform the subtraction:
> 
> PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;
> 
> Cc: Jaben Carsey <jaben.carsey@intel.com>
> Cc: Ruiyu Ni <ruiyu.ni@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Hao Wu <hao.a.wu@intel.com>
> Acked-by: Laszlo Ersek <lersek@redhat.com>
> ---
>  ShellPkg/Application/Shell/ShellParametersProtocol.c                | 6 +++---
>  ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c              | 4 ++--
>  ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
> | 4 ++--
>  ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c                   | 4 ++--
>  ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c                    | 4 ++--
>  5 files changed, 11 insertions(+), 11 deletions(-)
> 
> diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> index 4999155..8d76fb4 100644
> --- a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> +++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> @@ -5,7 +5,7 @@
>    (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
>    Copyright (C) 2014, Red Hat, Inc.
>    (C) Copyright 2013 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -1034,9 +1034,9 @@ UpdateStdInStdOutStdErr(
>    StrnCpyS(CommandLineCopy, StrSize(CommandLineCopy)/sizeof(CHAR16),
> NewCommandLine, StrLen(NewCommandLine));
> 
>    if (FirstLocation != CommandLineCopy + StrLen(CommandLineCopy)
> -    && ((UINTN)(FirstLocation - CommandLineCopy) <
> StrLen(NewCommandLine))
> +    && (((UINTN)FirstLocation - (UINTN)CommandLineCopy)/sizeof(CHAR16)
> < StrLen(NewCommandLine))
>      ){
> -    *(NewCommandLine + (UINTN)(FirstLocation - CommandLineCopy)) =
> CHAR_NULL;
> +    *(NewCommandLine + ((UINTN)FirstLocation -
> (UINTN)CommandLineCopy)/sizeof(CHAR16)) = CHAR_NULL;
>    }
> 
>    if (!EFI_ERROR(Status)) {
> diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> index bb2c0b9..18f15fa 100644
> --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> @@ -2,7 +2,7 @@
>    Main file for DmpStore shell Debug1 function.
> 
>    (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2005 - 2016, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -364,7 +364,7 @@ AppendSingleVariableToFile (
>    //
>    // Crc32
>    //
> -  gBS->CalculateCrc32 (Buffer, (UINTN) (Ptr - Buffer), (UINT32 *) Ptr);
> +  gBS->CalculateCrc32 (Buffer, (UINTN) Ptr - (UINTN) Buffer, (UINT32 *) Ptr);
> 
>    Status = ShellWriteFile (FileHandle, &BufferSize, Buffer);
>    FreePool (Buffer);
> diff --git
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> index 56b682a..a5b16fe 100644
> ---
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> +++
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> @@ -2,7 +2,7 @@
>    Tools of clarify the content of the smbios table.
> 
>    (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2005 - 2012, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -700,7 +700,7 @@ CalculateSmbios64BitStructureCountAndLength (
>      //
>      // Length = Next structure head - this structure head
>      //
> -    (*Smbios64TableLength) += (UINTN) (Smbios.Raw - Raw);
> +    (*Smbios64TableLength) += ((UINTN) Smbios.Raw - (UINTN) Raw);
>      if ((*Smbios64TableLength) > Smbios64EntryPoint->TableMaximumSize) {
>      	//
>      	// The actual table length exceeds maximum table size,
> diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> index d17a29d..0bcee92 100644
> --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> @@ -75,7 +75,7 @@ IsValidGuidString(
>         ) {
>        Walker++;
>      } else {
> -      if (*Walker == L'-' && (UINTN)(Walker - PrevWalker) ==
> mGuidDataLen[Index]) {
> +      if (*Walker == L'-' && (((UINTN)Walker - (UINTN)PrevWalker) / sizeof
> (CHAR16)) == mGuidDataLen[Index]) {
>          Walker++;
>          PrevWalker = Walker;
>          Index++;
> @@ -85,7 +85,7 @@ IsValidGuidString(
>      }
>    }
> 
> -  if ((UINTN)(Walker - PrevWalker) == mGuidDataLen[Index]) {
> +  if ((((UINTN)Walker - (UINTN)PrevWalker) / sizeof (CHAR16)) ==
> mGuidDataLen[Index]) {
>      return TRUE;
>    } else {
>      return FALSE;
> diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> index dd4a740..9ae8176 100644
> --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> @@ -99,10 +99,10 @@ IsCurrentFileSystem (
> 
>    Splitter2 = StrStr (Cwd, L":");
> 
> -  if ((UINTN) (Splitter1 - FullPath) != (UINTN) (Splitter2 - Cwd)) {
> +  if (((UINTN) Splitter1 - (UINTN) FullPath) != ((UINTN) Splitter2 - (UINTN)
> Cwd)) {
>      return FALSE;
>    } else {
> -    if (StrniCmp (FullPath, Cwd, (UINTN) (Splitter1 - FullPath)) == NULL) {
> +    if (StrniCmp (FullPath, Cwd, ((UINTN) Splitter1 - (UINTN) FullPath) / sizeof
> (CHAR16)) == NULL) {
>        return TRUE;
>      } else {
>        return FALSE;
> --
> 1.9.5.msysgit.0



^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 6/6] ShellPkg: " Hao Wu
  2017-02-27  5:10   ` Ni, Ruiyu
  2017-02-27  7:18   ` Ni, Ruiyu
@ 2017-02-27 16:38   ` Carsey, Jaben
  2 siblings, 0 replies; 18+ messages in thread
From: Carsey, Jaben @ 2017-02-27 16:38 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Ni, Ruiyu, Carsey, Jaben

Reviewed-by: Jaben Carsey <jaben.carsey@intel.com>

> -----Original Message-----
> From: Wu, Hao A
> Sent: Friday, February 24, 2017 8:05 PM
> To: edk2-devel@lists.01.org
> Cc: Wu, Hao A <hao.a.wu@intel.com>; Carsey, Jaben
> <jaben.carsey@intel.com>; Ni, Ruiyu <ruiyu.ni@intel.com>
> Subject: [PATCH v3 6/6] ShellPkg: Refine type cast for pointer subtraction
> Importance: High
> 
> For pointer subtraction, the result is of type "ptrdiff_t". According to
> the C11 standard (Committee Draft - April 12, 2011):
> 
> "When two pointers are subtracted, both shall point to elements of the
> same array object, or one past the last element of the array object; the
> result is the difference of the subscripts of the two array elements. The
> size of the result is implementation-defined, and its type (a signed
> integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
> is not representable in an object of that type, the behavior is
> undefined."
> 
> In our codes, there are cases that the pointer subtraction is not
> performed by pointers to elements of the same array object. This might
> lead to potential issues, since the behavior is undefined according to C11
> standard.
> 
> Also, since the size of type "ptrdiff_t" is implementation-defined. Some
> static code checkers may warn that the pointer subtraction might underflow
> first and then being cast to a bigger size. For example:
> 
> UINT8  *Ptr1, *Ptr2;
> UINTN  PtrDiff;
> ...
> PtrDiff = (UINTN) (Ptr1 - Ptr2);
> 
> The commit will refine the pointer subtraction expressions by casting each
> pointer to UINTN first and then perform the subtraction:
> 
> PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;
> 
> Cc: Jaben Carsey <jaben.carsey@intel.com>
> Cc: Ruiyu Ni <ruiyu.ni@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Hao Wu <hao.a.wu@intel.com>
> Acked-by: Laszlo Ersek <lersek@redhat.com>
> ---
>  ShellPkg/Application/Shell/ShellParametersProtocol.c                | 6 +++---
>  ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c              | 4 ++--
>  ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView.c
> | 4 ++--
>  ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c                   | 4 ++--
>  ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c                    | 4 ++--
>  5 files changed, 11 insertions(+), 11 deletions(-)
> 
> diff --git a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> index 4999155..8d76fb4 100644
> --- a/ShellPkg/Application/Shell/ShellParametersProtocol.c
> +++ b/ShellPkg/Application/Shell/ShellParametersProtocol.c
> @@ -5,7 +5,7 @@
>    (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
>    Copyright (C) 2014, Red Hat, Inc.
>    (C) Copyright 2013 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -1034,9 +1034,9 @@ UpdateStdInStdOutStdErr(
>    StrnCpyS(CommandLineCopy, StrSize(CommandLineCopy)/sizeof(CHAR16),
> NewCommandLine, StrLen(NewCommandLine));
> 
>    if (FirstLocation != CommandLineCopy + StrLen(CommandLineCopy)
> -    && ((UINTN)(FirstLocation - CommandLineCopy) <
> StrLen(NewCommandLine))
> +    && (((UINTN)FirstLocation - (UINTN)CommandLineCopy)/sizeof(CHAR16)
> < StrLen(NewCommandLine))
>      ){
> -    *(NewCommandLine + (UINTN)(FirstLocation - CommandLineCopy)) =
> CHAR_NULL;
> +    *(NewCommandLine + ((UINTN)FirstLocation -
> (UINTN)CommandLineCopy)/sizeof(CHAR16)) = CHAR_NULL;
>    }
> 
>    if (!EFI_ERROR(Status)) {
> diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> index bb2c0b9..18f15fa 100644
> --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/DmpStore.c
> @@ -2,7 +2,7 @@
>    Main file for DmpStore shell Debug1 function.
> 
>    (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2005 - 2016, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -364,7 +364,7 @@ AppendSingleVariableToFile (
>    //
>    // Crc32
>    //
> -  gBS->CalculateCrc32 (Buffer, (UINTN) (Ptr - Buffer), (UINT32 *) Ptr);
> +  gBS->CalculateCrc32 (Buffer, (UINTN) Ptr - (UINTN) Buffer, (UINT32 *) Ptr);
> 
>    Status = ShellWriteFile (FileHandle, &BufferSize, Buffer);
>    FreePool (Buffer);
> diff --git
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> index 56b682a..a5b16fe 100644
> ---
> a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> +++
> b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/SmbiosView
> .c
> @@ -2,7 +2,7 @@
>    Tools of clarify the content of the smbios table.
> 
>    (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
> -  Copyright (c) 2005 - 2012, Intel Corporation. All rights reserved.<BR>
> +  Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
>    This program and the accompanying materials
>    are licensed and made available under the terms and conditions of the BSD
> License
>    which accompanies this distribution.  The full text of the license may be
> found at
> @@ -700,7 +700,7 @@ CalculateSmbios64BitStructureCountAndLength (
>      //
>      // Length = Next structure head - this structure head
>      //
> -    (*Smbios64TableLength) += (UINTN) (Smbios.Raw - Raw);
> +    (*Smbios64TableLength) += ((UINTN) Smbios.Raw - (UINTN) Raw);
>      if ((*Smbios64TableLength) > Smbios64EntryPoint->TableMaximumSize) {
>      	//
>      	// The actual table length exceeds maximum table size,
> diff --git a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> index d17a29d..0bcee92 100644
> --- a/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> +++ b/ShellPkg/Library/UefiShellDriver1CommandsLib/Dh.c
> @@ -75,7 +75,7 @@ IsValidGuidString(
>         ) {
>        Walker++;
>      } else {
> -      if (*Walker == L'-' && (UINTN)(Walker - PrevWalker) ==
> mGuidDataLen[Index]) {
> +      if (*Walker == L'-' && (((UINTN)Walker - (UINTN)PrevWalker) / sizeof
> (CHAR16)) == mGuidDataLen[Index]) {
>          Walker++;
>          PrevWalker = Walker;
>          Index++;
> @@ -85,7 +85,7 @@ IsValidGuidString(
>      }
>    }
> 
> -  if ((UINTN)(Walker - PrevWalker) == mGuidDataLen[Index]) {
> +  if ((((UINTN)Walker - (UINTN)PrevWalker) / sizeof (CHAR16)) ==
> mGuidDataLen[Index]) {
>      return TRUE;
>    } else {
>      return FALSE;
> diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> index dd4a740..9ae8176 100644
> --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Cd.c
> @@ -99,10 +99,10 @@ IsCurrentFileSystem (
> 
>    Splitter2 = StrStr (Cwd, L":");
> 
> -  if ((UINTN) (Splitter1 - FullPath) != (UINTN) (Splitter2 - Cwd)) {
> +  if (((UINTN) Splitter1 - (UINTN) FullPath) != ((UINTN) Splitter2 - (UINTN)
> Cwd)) {
>      return FALSE;
>    } else {
> -    if (StrniCmp (FullPath, Cwd, (UINTN) (Splitter1 - FullPath)) == NULL) {
> +    if (StrniCmp (FullPath, Cwd, ((UINTN) Splitter1 - (UINTN) FullPath) / sizeof
> (CHAR16)) == NULL) {
>        return TRUE;
>      } else {
>        return FALSE;
> --
> 1.9.5.msysgit.0



^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 4/6] NetworkPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 4/6] NetworkPkg: " Hao Wu
@ 2017-03-06  1:03   ` Fu, Siyuan
  2017-03-06  1:14   ` Wu, Jiaxin
  1 sibling, 0 replies; 18+ messages in thread
From: Fu, Siyuan @ 2017-03-06  1:03 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Wu, Jiaxin

Reviewed-by: Fu Siyuan <siyuan.fu@intel.com>


-----Original Message-----
From: Wu, Hao A 
Sent: 2017年2月25日 12:05
To: edk2-devel@lists.01.org
Cc: Wu, Hao A <hao.a.wu@intel.com>; Fu, Siyuan <siyuan.fu@intel.com>; Wu, Jiaxin <jiaxin.wu@intel.com>
Subject: [PATCH v3 4/6] NetworkPkg: Refine type cast for pointer subtraction

For pointer subtraction, the result is of type "ptrdiff_t". According to the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined."

In our codes, there are cases that the pointer subtraction is not performed by pointers to elements of the same array object. This might lead to potential issues, since the behavior is undefined according to C11 standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some static code checkers may warn that the pointer subtraction might underflow first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Siyuan Fu <siyuan.fu@intel.com>
Cc: Jiaxin Wu <jiaxin.wu@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 NetworkPkg/HttpDxe/HttpImpl.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/NetworkPkg/HttpDxe/HttpImpl.c b/NetworkPkg/HttpDxe/HttpImpl.c index 745832b..1f7a4fa 100644
--- a/NetworkPkg/HttpDxe/HttpImpl.c
+++ b/NetworkPkg/HttpDxe/HttpImpl.c
@@ -1342,7 +1342,7 @@ HttpResponseWorker (
     // We receive part of header of next HTTP msg.
     //
     if (HttpInstance->NextMsg != NULL) {
-      HttpMsg->BodyLength = MIN ((UINTN) (HttpInstance->NextMsg - (CHAR8 *) Fragment.Bulk), HttpMsg->BodyLength);
+      HttpMsg->BodyLength = MIN ((UINTN) HttpInstance->NextMsg - 
+ (UINTN) Fragment.Bulk, HttpMsg->BodyLength);
       CopyMem (HttpMsg->Body, Fragment.Bulk, HttpMsg->BodyLength);
       
       HttpInstance->CacheLen = Fragment.Len - HttpMsg->BodyLength; @@ -1360,7 +1360,7 @@ HttpResponseWorker (
         CopyMem (HttpInstance->CacheBody, Fragment.Bulk + HttpMsg->BodyLength, HttpInstance->CacheLen);
         HttpInstance->CacheOffset = 0;
 
-        HttpInstance->NextMsg = HttpInstance->CacheBody + (UINTN) (HttpInstance->NextMsg - (CHAR8 *) (Fragment.Bulk + HttpMsg->BodyLength));
+        HttpInstance->NextMsg = HttpInstance->CacheBody + ((UINTN) 
+ HttpInstance->NextMsg - (UINTN) (Fragment.Bulk + 
+ HttpMsg->BodyLength));
       }
     } else {
       HttpMsg->BodyLength = MIN (Fragment.Len, (UINT32) HttpMsg->BodyLength);
--
1.9.5.msysgit.0


^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 4/6] NetworkPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 4/6] NetworkPkg: " Hao Wu
  2017-03-06  1:03   ` Fu, Siyuan
@ 2017-03-06  1:14   ` Wu, Jiaxin
  1 sibling, 0 replies; 18+ messages in thread
From: Wu, Jiaxin @ 2017-03-06  1:14 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Fu, Siyuan

Reviewed-by: Wu Jiaxin <jiaxin.wu@intel.com>


> -----Original Message-----
> From: Wu, Hao A
> Sent: Saturday, February 25, 2017 12:05 PM
> To: edk2-devel@lists.01.org
> Cc: Wu, Hao A <hao.a.wu@intel.com>; Fu, Siyuan <siyuan.fu@intel.com>;
> Wu, Jiaxin <jiaxin.wu@intel.com>
> Subject: [PATCH v3 4/6] NetworkPkg: Refine type cast for pointer subtraction
> 
> For pointer subtraction, the result is of type "ptrdiff_t". According to
> the C11 standard (Committee Draft - April 12, 2011):
> 
> "When two pointers are subtracted, both shall point to elements of the
> same array object, or one past the last element of the array object; the
> result is the difference of the subscripts of the two array elements. The
> size of the result is implementation-defined, and its type (a signed
> integer type) is ptrdiff_t defined in the <stddef.h> header. If the result
> is not representable in an object of that type, the behavior is
> undefined."
> 
> In our codes, there are cases that the pointer subtraction is not
> performed by pointers to elements of the same array object. This might
> lead to potential issues, since the behavior is undefined according to C11
> standard.
> 
> Also, since the size of type "ptrdiff_t" is implementation-defined. Some
> static code checkers may warn that the pointer subtraction might underflow
> first and then being cast to a bigger size. For example:
> 
> UINT8  *Ptr1, *Ptr2;
> UINTN  PtrDiff;
> ...
> PtrDiff = (UINTN) (Ptr1 - Ptr2);
> 
> The commit will refine the pointer subtraction expressions by casting each
> pointer to UINTN first and then perform the subtraction:
> 
> PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;
> 
> Cc: Siyuan Fu <siyuan.fu@intel.com>
> Cc: Jiaxin Wu <jiaxin.wu@intel.com>
> Contributed-under: TianoCore Contribution Agreement 1.0
> Signed-off-by: Hao Wu <hao.a.wu@intel.com>
> Acked-by: Laszlo Ersek <lersek@redhat.com>
> ---
>  NetworkPkg/HttpDxe/HttpImpl.c | 4 ++--
>  1 file changed, 2 insertions(+), 2 deletions(-)
> 
> diff --git a/NetworkPkg/HttpDxe/HttpImpl.c
> b/NetworkPkg/HttpDxe/HttpImpl.c
> index 745832b..1f7a4fa 100644
> --- a/NetworkPkg/HttpDxe/HttpImpl.c
> +++ b/NetworkPkg/HttpDxe/HttpImpl.c
> @@ -1342,7 +1342,7 @@ HttpResponseWorker (
>      // We receive part of header of next HTTP msg.
>      //
>      if (HttpInstance->NextMsg != NULL) {
> -      HttpMsg->BodyLength = MIN ((UINTN) (HttpInstance->NextMsg -
> (CHAR8 *) Fragment.Bulk), HttpMsg->BodyLength);
> +      HttpMsg->BodyLength = MIN ((UINTN) HttpInstance->NextMsg -
> (UINTN) Fragment.Bulk, HttpMsg->BodyLength);
>        CopyMem (HttpMsg->Body, Fragment.Bulk, HttpMsg->BodyLength);
> 
>        HttpInstance->CacheLen = Fragment.Len - HttpMsg->BodyLength;
> @@ -1360,7 +1360,7 @@ HttpResponseWorker (
>          CopyMem (HttpInstance->CacheBody, Fragment.Bulk + HttpMsg-
> >BodyLength, HttpInstance->CacheLen);
>          HttpInstance->CacheOffset = 0;
> 
> -        HttpInstance->NextMsg = HttpInstance->CacheBody + (UINTN)
> (HttpInstance->NextMsg - (CHAR8 *) (Fragment.Bulk + HttpMsg-
> >BodyLength));
> +        HttpInstance->NextMsg = HttpInstance->CacheBody + ((UINTN)
> HttpInstance->NextMsg - (UINTN) (Fragment.Bulk + HttpMsg->BodyLength));
>        }
>      } else {
>        HttpMsg->BodyLength = MIN (Fragment.Len, (UINT32) HttpMsg-
> >BodyLength);
> --
> 1.9.5.msysgit.0



^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 5/6] SecurityPkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 5/6] SecurityPkg: " Hao Wu
@ 2017-03-06  1:29   ` Zhang, Chao B
  0 siblings, 0 replies; 18+ messages in thread
From: Zhang, Chao B @ 2017-03-06  1:29 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org

Reviewed-by: Chao Zhang<chao.b.zhang@intel.com>

-----Original Message-----
From: Wu, Hao A 
Sent: Saturday, February 25, 2017 12:05 PM
To: edk2-devel@lists.01.org
Cc: Wu, Hao A <hao.a.wu@intel.com>; Zhang, Chao B <chao.b.zhang@intel.com>
Subject: [PATCH v3 5/6] SecurityPkg: Refine type cast for pointer subtraction

For pointer subtraction, the result is of type "ptrdiff_t". According to the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined."

In our codes, there are cases that the pointer subtraction is not performed by pointers to elements of the same array object. This might lead to potential issues, since the behavior is undefined according to C11 standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some static code checkers may warn that the pointer subtraction might underflow first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Chao Zhang <chao.b.zhang@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c        | 16 ++++++++--------
 SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c              | 10 +++++-----
 SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c                                |  6 +++---
 SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c                                  | 10 +++++-----
 SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c                                  | 10 +++++-----
 SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c | 12 ++++++------
 6 files changed, 32 insertions(+), 32 deletions(-)

diff --git a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
index e28e106..588072c 100644
--- a/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.c
+++ b/SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLi
+++ b.c
@@ -391,13 +391,13 @@ HashPeImage (
     //
     // Use PE32 offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - 
+ (UINTN) HashBase;
     NumberOfRvaAndSizes = mNtHeader.Pe32->OptionalHeader.NumberOfRvaAndSizes;
   } else if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
     //
     // Use PE32+ offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - 
+ (UINTN) HashBase;
     NumberOfRvaAndSizes = mNtHeader.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
   } else {
     //
@@ -425,13 +425,13 @@ HashPeImage (
       // Use PE32 offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - 
+ ((UINTN) HashBase - (UINTN) mImageBase);
     } else {
       //
       // Use PE32+ offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - 
+ ((UINTN) HashBase - (UINTN) mImageBase);
     }
 
     if (HashSize != 0) {
@@ -449,13 +449,13 @@ HashPeImage (
       // Use PE32 offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENT
+ RY_SECURITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY
+ _ENTRY_SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
@@ -474,13 +474,13 @@ HashPeImage (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - 
+ ((UINTN) HashBase - (UINTN) mImageBase);
     } else {
       //
       // Use PE32+ offset.
       //
       HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) (HashBase - mImageBase);
+      HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - 
+ ((UINTN) HashBase - (UINTN) mImageBase);
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c b/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c
index 52bf582..8167a21 100644
--- a/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c
+++ b/SecurityPkg/Library/DxeTpmMeasureBootLib/DxeTpmMeasureBootLib.c
@@ -15,7 +15,7 @@
   TcgMeasureGptTable() function will receive untrusted GPT partition table, and parse
   partition data carefully.
 
-Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -443,13 +443,13 @@ TcgMeasurePeImage (
     // Use PE32 offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN) 
+ HashBase;
   } else {
     //
     // Use PE32+ offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.CheckSum) - 
+ (UINTN) HashBase;
   }
 
   HashStatus = Sha1Update (Sha1Ctx, HashBase, HashSize); @@ -494,13 +494,13 @@ TcgMeasurePeImage (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SEC
+ URITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset
       //    
       HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY
+ _SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c b/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c
index 64d3c53..180f360 100644
--- a/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c
+++ b/SecurityPkg/Library/Tpm2CommandLib/Tpm2Help.c
@@ -1,7 +1,7 @@
 /** @file
   Implement TPM2 help.
 
-Copyright (c) 2013 - 2016, Intel Corporation. All rights reserved. <BR>
+Copyright (c) 2013 - 2017, Intel Corporation. All rights reserved. <BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -141,7 +141,7 @@ CopyAuthSessionCommand (
     Buffer += sizeof(UINT16);
   }
 
-  return (UINT32)(UINTN)(Buffer - (UINT8 *)AuthSessionOut);
+  return (UINT32)((UINTN)Buffer - (UINTN)AuthSessionOut);
 }
 
 /**
@@ -186,7 +186,7 @@ CopyAuthSessionResponse (
   CopyMem (AuthSessionOut->hmac.buffer, Buffer, AuthSessionOut->hmac.size);
   Buffer += AuthSessionOut->hmac.size;
 
-  return (UINT32)(UINTN)(Buffer - (UINT8 *)AuthSessionIn);
+  return (UINT32)((UINTN)Buffer - (UINTN)AuthSessionIn);
 }
 
 /**
diff --git a/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c b/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c
index de55ed9..8ee34a7 100644
--- a/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c
+++ b/SecurityPkg/Tcg/Tcg2Dxe/MeasureBootPeCoff.c
@@ -6,7 +6,7 @@
   This external input must be validated carefully to avoid security issue like
   buffer overflow, integer overflow.
 
-Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -206,13 +206,13 @@ MeasurePeImageAndExtend (
     // Use PE32 offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN) 
+ HashBase;
   } else {
     //
     // Use PE32+ offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.CheckSum) - 
+ (UINTN) HashBase;
   }
 
   Status = HashUpdate (HashHandle, HashBase, HashSize); @@ -257,13 +257,13 @@ MeasurePeImageAndExtend (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SEC
+ URITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset
       //    
       HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY
+ _SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c b/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c
index b20fc70..a7de588 100644
--- a/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c
+++ b/SecurityPkg/Tcg/TrEEDxe/MeasureBootPeCoff.c
@@ -6,7 +6,7 @@
   This external input must be validated carefully to avoid security issue like
   buffer overflow, integer overflow.
 
-Copyright (c) 2013 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2013 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -206,13 +206,13 @@ MeasurePeImageAndExtend (
     // Use PE32 offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32->OptionalHeader.CheckSum) - (UINTN) 
+ HashBase;
   } else {
     //
     // Use PE32+ offset
     //
     NumberOfRvaAndSizes = Hdr.Pe32Plus->OptionalHeader.NumberOfRvaAndSizes;
-    HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&Hdr.Pe32Plus->OptionalHeader.CheckSum) - 
+ (UINTN) HashBase;
   }
 
   Status = HashUpdate (HashHandle, HashBase, HashSize); @@ -257,13 +257,13 @@ MeasurePeImageAndExtend (
       // Use PE32 offset
       //
       HashBase = (UINT8 *) &Hdr.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&Hdr.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SEC
+ URITY]) - (UINTN) HashBase;
     } else {
       //
       // Use PE32+ offset
       //    
       HashBase = (UINT8 *) &Hdr.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-      HashSize = (UINTN) ((UINT8 *)(&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+      HashSize = (UINTN) 
+ (&Hdr.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY
+ _SECURITY]) - (UINTN) HashBase;
     }
 
     if (HashSize != 0) {
diff --git a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
index 6f58729..52804dd 100644
--- a/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigImpl.c
+++ b/SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootCo
+++ nfigImpl.c
@@ -1837,12 +1837,12 @@ HashPeImage (
     //
     // Use PE32 offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32->OptionalHeader.CheckSum) - 
+ (UINTN) HashBase;
   } else {
     //
     // Use PE32+ offset.
     //
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - HashBase);
+    HashSize = (UINTN) (&mNtHeader.Pe32Plus->OptionalHeader.CheckSum) - 
+ (UINTN) HashBase;
   }
 
   Status  = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); @@ -1859,13 +1859,13 @@ HashPeImage (
     // Use PE32 offset.
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.CheckSum + sizeof (UINT32);
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+    HashSize = (UINTN) 
+ (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENT
+ RY_SECURITY]) - (UINTN) HashBase;
   } else {
     //
     // Use PE32+ offset.
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.CheckSum + sizeof (UINT32);
-    HashSize = (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY]) - HashBase);
+    HashSize = (UINTN) 
+ (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY
+ _ENTRY_SECURITY]) - (UINTN) HashBase;
   }
 
   Status  = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize); @@ -1881,13 +1881,13 @@ HashPeImage (
     // Use PE32 offset
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-    HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - (UINTN) ((UINT8 *) (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - mImageBase);
+    HashSize = mNtHeader.Pe32->OptionalHeader.SizeOfHeaders - ((UINTN) 
+ (&mNtHeader.Pe32->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENT
+ RY_SECURITY + 1]) - (UINTN) mImageBase);
   } else {
     //
     // Use PE32+ offset.
     //
     HashBase = (UINT8 *) &mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1];
-    HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - (UINTN) ((UINT8 *) (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_SECURITY + 1]) - mImageBase);
+    HashSize = mNtHeader.Pe32Plus->OptionalHeader.SizeOfHeaders - 
+ ((UINTN) 
+ (&mNtHeader.Pe32Plus->OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY
+ _ENTRY_SECURITY + 1]) - (UINTN) mImageBase);
   }
 
   Status  = mHash[HashAlg].HashUpdate(HashCtx, HashBase, HashSize);
--
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

* Re: [PATCH v3 1/6] MdeModulePkg: Refine type cast for pointer subtraction
  2017-02-25  4:05 ` [PATCH v3 1/6] MdeModulePkg: " Hao Wu
@ 2017-03-06  1:37   ` Tian, Feng
  0 siblings, 0 replies; 18+ messages in thread
From: Tian, Feng @ 2017-03-06  1:37 UTC (permalink / raw)
  To: Wu, Hao A, edk2-devel@lists.01.org; +Cc: Zeng, Star, Tian, Feng

Reviewed-by: Feng Tian <feng.tian@intel.com>

Thanks
Feng

-----Original Message-----
From: Wu, Hao A 
Sent: Saturday, February 25, 2017 12:05 PM
To: edk2-devel@lists.01.org
Cc: Wu, Hao A <hao.a.wu@intel.com>; Tian, Feng <feng.tian@intel.com>; Zeng, Star <star.zeng@intel.com>
Subject: [PATCH v3 1/6] MdeModulePkg: Refine type cast for pointer subtraction

For pointer subtraction, the result is of type "ptrdiff_t". According to the C11 standard (Committee Draft - April 12, 2011):

"When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined."

In our codes, there are cases that the pointer subtraction is not performed by pointers to elements of the same array object. This might lead to potential issues, since the behavior is undefined according to C11 standard.

Also, since the size of type "ptrdiff_t" is implementation-defined. Some static code checkers may warn that the pointer subtraction might underflow first and then being cast to a bigger size. For example:

UINT8  *Ptr1, *Ptr2;
UINTN  PtrDiff;
...
PtrDiff = (UINTN) (Ptr1 - Ptr2);

The commit will refine the pointer subtraction expressions by casting each pointer to UINTN first and then perform the subtraction:

PtrDiff = (UINTN) Ptr1 - (UINTN) Ptr2;

Cc: Feng Tian <feng.tian@intel.com>
Cc: Star Zeng <star.zeng@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.0
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
Acked-by: Laszlo Ersek <lersek@redhat.com>
---
 MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c              |  4 ++--
 MdeModulePkg/Include/Library/NetLib.h                             |  6 +++---
 MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c             |  4 ++--
 MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c         |  2 +-
 MdeModulePkg/Library/FileExplorerLib/FileExplorer.c               |  4 ++--
 MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c        |  4 ++--
 MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c            |  4 ++--
 MdeModulePkg/Universal/DebugPortDxe/DebugPort.c                   |  4 ++--
 MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c |  4 ++--
 MdeModulePkg/Universal/HiiDatabaseDxe/Image.c                     |  4 ++--
 MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c             | 10 +++++-----
 11 files changed, 25 insertions(+), 25 deletions(-)

diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c
index 2bc4f8c..d2ad94e 100644
--- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c
+++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c
@@ -1,7 +1,7 @@
 /** @file
   PCI Rom supporting funtions implementation for PCI Bus module.
 
-Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -776,7 +776,7 @@ ProcessOpRomImage (
 NextImage:
     RomBarOffset += ImageSize;
 
-  } while (((Indicator & 0x80) == 0x00) && ((UINTN) (RomBarOffset - (UINT8 *) RomBar) < PciDevice->RomSize));
+  } while (((Indicator & 0x80) == 0x00) && (((UINTN) RomBarOffset - 
+ (UINTN) RomBar) < PciDevice->RomSize));
 
   return RetStatus;
 }
diff --git a/MdeModulePkg/Include/Library/NetLib.h b/MdeModulePkg/Include/Library/NetLib.h
index 09ead09..3b8ff1a 100644
--- a/MdeModulePkg/Include/Library/NetLib.h
+++ b/MdeModulePkg/Include/Library/NetLib.h
@@ -2,7 +2,7 @@
   This library is only intended to be used by UEFI network stack modules.
   It provides basic functions for the UEFI network stack.
 
-Copyright (c) 2005 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at<BR> @@ -1610,10 +1610,10 @@ typedef struct {
   (sizeof (NET_BUF) + ((BlockOpNum) - 1) * sizeof (NET_BLOCK_OP))
 
 #define NET_HEADSPACE(BlockOp)  \
-  (UINTN)((BlockOp)->Head - (BlockOp)->BlockHead)
+  ((UINTN)((BlockOp)->Head) - (UINTN)((BlockOp)->BlockHead))
 
 #define NET_TAILSPACE(BlockOp)  \
-  (UINTN)((BlockOp)->BlockTail - (BlockOp)->Tail)
+  ((UINTN)((BlockOp)->BlockTail) - (UINTN)((BlockOp)->Tail))
 
 /**
   Allocate a single block NET_BUF. Upon allocation, all the diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c
index 71e05bd..d7abcc8 100644
--- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c
+++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c
@@ -10,7 +10,7 @@
   ValidateFmpCapsule(), DisplayCapsuleImage(), ConvertBmpToGopBlt() will
   receive untrusted input and do basic validation.
 
-  Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2016 - 2017, Intel Corporation. All rights 
+ reserved.<BR>
   This program and the accompanying materials
   are licensed and made available under the terms and conditions of the BSD License
   which accompanies this distribution.  The full text of the license may be found at @@ -547,7 +547,7 @@ ConvertBmpToGopBlt (
 
     }
 
-    ImageIndex = (UINTN) (Image - ImageHeader);
+    ImageIndex = (UINTN) Image - (UINTN) ImageHeader;
     if ((ImageIndex % 4) != 0) {
       //
       // Bmp Image starts each row on a 32-bit boundary!
diff --git a/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c b/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c
index 589d4db..d9aeb92 100644
--- a/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c
+++ b/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c
@@ -226,7 +226,7 @@ DxePrintLibPrint2ProtocolVaListToBaseList (
     //
     // If BASE_LIST is larger than Size, then return FALSE
     //
-    if ((UINTN)((UINT8 *)BaseListMarker - (UINT8 *)BaseListStart) > Size) {
+    if (((UINTN)BaseListMarker - (UINTN)BaseListStart) > Size) {
       DEBUG ((DEBUG_ERROR, "The input variable argument list is too long. Please consider breaking into multiple print calls.\n"));
       return FALSE;
     }
diff --git a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c
index 5eedad7..9182751 100644
--- a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c
+++ b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c
@@ -728,7 +728,7 @@ LibAppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 3);
-      StrCpyS (LastSlash, MaxLen - (UINTN) (LastSlash - Str), TmpStr);
+      StrCpyS (LastSlash, MaxLen - ((UINTN) LastSlash - (UINTN) Str) / 
+ sizeof (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '\\') {
       //
@@ -740,7 +740,7 @@ LibAppendFileName (
       // that overlap.
       //
       StrCpyS (TmpStr, MaxLen, Ptr + 2);
-      StrCpyS (Ptr, MaxLen - (UINTN) (Ptr - Str), TmpStr);
+      StrCpyS (Ptr, MaxLen - ((UINTN) Ptr - (UINTN) Str) / sizeof 
+ (CHAR16), TmpStr);
       Ptr = LastSlash;
     } else if (*Ptr == '\\') {
       LastSlash = Ptr;
diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c
index 5698c91..1f8aaf4 100644
--- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c
+++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c
@@ -1,7 +1,7 @@
 /** @file
   Save the S3 data to S3 boot script.
 
-  Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+  Copyright (c) 2006 - 2017, Intel Corporation. All rights 
+ reserved.<BR>
 
   This program and the accompanying materials
   are licensed and made available under the terms and conditions @@ -2025,7 +2025,7 @@ S3BootScriptCalculateInsertAddress (
    // calculate the Position offset
    //
    if (Position != NULL) {
-     PositionOffset = (UINTN) ((UINT8 *)Position - S3TableBase);
+     PositionOffset = (UINTN)Position - (UINTN)S3TableBase;
 
      //
      // If the BeforeOrAfter is FALSE, that means to insert the node right after the node.
diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c b/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c
index 6f705bd..116cf28 100644
--- a/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c
+++ b/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c
@@ -1,7 +1,7 @@
 /** @file
   Load option library functions which relate with creating and processing load options.
 
-Copyright (c) 2011 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2011 - 2017, Intel Corporation. All rights reserved.<BR>
 (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP<BR>  This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License @@ -912,7 +912,7 @@ EfiBootManagerVariableToLoadOptionEx (
   FilePath = (EFI_DEVICE_PATH_PROTOCOL *) VariablePtr;
   VariablePtr += FilePathSize;
 
-  OptionalDataSize = (UINT32) (VariableSize - (UINTN) (VariablePtr - Variable));
+  OptionalDataSize = (UINT32) (VariableSize - ((UINTN) VariablePtr - 
+ (UINTN) Variable));
   if (OptionalDataSize == 0) {
     OptionalData = NULL;
   } else {
diff --git a/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c b/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c
index 298b6b2..dcb623c 100644
--- a/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c
+++ b/MdeModulePkg/Universal/DebugPortDxe/DebugPort.c
@@ -4,7 +4,7 @@
   ALL CODE IN THE SERIALIO STACK MUST BE RE-ENTRANT AND CALLABLE FROM
   INTERRUPT CONTEXT
 
-Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -569,7 +569,7 @@ DebugPortRead (
     LocalBufferSize = *BufferSize - (BufferPtr - (UINT8 *) Buffer);
   } while (LocalBufferSize != 0 && Timeout > 0);
 
-  *BufferSize = (UINTN) (BufferPtr - (UINT8 *) Buffer);
+  *BufferSize = (UINTN) BufferPtr - (UINTN) Buffer;
 
   return Status;
 }
diff --git a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c
index 2e3e8c7..49e747b 100644
--- a/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c
+++ b/MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c
@@ -3,7 +3,7 @@
   These are the common Fault Tolerant Write (FTW) functions that are shared 
   by DXE FTW driver and SMM FTW driver.
 
-Copyright (c) 2006 - 2015, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials                          
 are licensed and made available under the terms and conditions of the BSD License         
 which accompanies this distribution.  The full text of the license may be found at        
@@ -373,7 +373,7 @@ FtwWrite (
   //
   // If Record is out of the range of Header, return access denied.
   //
-  if (((UINTN)((UINT8 *) Record - (UINT8 *) Header)) > FTW_WRITE_TOTAL_SIZE (Header->NumberOfWrites - 1, Header->PrivateDataSize)) {
+  if (((UINTN) Record - (UINTN) Header) > FTW_WRITE_TOTAL_SIZE 
+ (Header->NumberOfWrites - 1, Header->PrivateDataSize)) {
     return EFI_ACCESS_DENIED;
   }
 
diff --git a/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c b/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c
index 1668828..e2fa16e 100644
--- a/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c
+++ b/MdeModulePkg/Universal/HiiDatabaseDxe/Image.c
@@ -2,7 +2,7 @@
 Implementation for EFI_HII_IMAGE_PROTOCOL.
 
 
-Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.<BR>
 This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License  which accompanies this distribution.  The full text of the license may be found at @@ -1124,7 +1124,7 @@ HiiSetImage (
     return EFI_OUT_OF_RESOURCES;
   }
 
-  Part1Size = (UINT32) (UINTN) ((UINT8 *) CurrentImageBlock - (UINT8 *) ImagePackage->ImageBlock);
+  Part1Size = (UINT32) ((UINTN) CurrentImageBlock - (UINTN) 
+ ImagePackage->ImageBlock);
   Part2Size = ImagePackage->ImageBlockSize - Part1Size - OldBlockSize;
   CopyMem (ImageBlocks, ImagePackage->ImageBlock, Part1Size);
 
diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
index f5b6a5f..b0c7434 100644
--- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
+++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c
@@ -16,7 +16,7 @@
   VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow,
   integer overflow. It should also check attribute to avoid authentication bypass.
 
-Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>  This program and the accompanying materials  are licensed and made available under the terms and conditions of the BSD License @@ -1170,7 +1170,7 @@ Reclaim (
   // Install the new variable if it is not NULL.
   //
   if (NewVariable != NULL) {
-    if ((UINTN) (CurrPtr - ValidBuffer) + NewVariableSize > VariableStoreHeader->Size) {
+    if (((UINTN) CurrPtr - (UINTN) ValidBuffer) + NewVariableSize > 
+ VariableStoreHeader->Size) {
       //
       // No enough space to store the new variable.
       //
@@ -1211,8 +1211,8 @@ Reclaim (
     // If volatile variable store, just copy valid buffer.
     //
     SetMem ((UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size, 0xff);
-    CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) (CurrPtr - ValidBuffer));
-    *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);
+    CopyMem ((UINT8 *) (UINTN) VariableBase, ValidBuffer, (UINTN) CurrPtr - (UINTN) ValidBuffer);
+    *LastVariableOffset = (UINTN) CurrPtr - (UINTN) ValidBuffer;
     Status  = EFI_SUCCESS;
   } else {
     //
@@ -1223,7 +1223,7 @@ Reclaim (
               (VARIABLE_STORE_HEADER *) ValidBuffer
               );
     if (!EFI_ERROR (Status)) {
-      *LastVariableOffset = (UINTN) (CurrPtr - ValidBuffer);
+      *LastVariableOffset = (UINTN) CurrPtr - (UINTN) ValidBuffer;
       mVariableModuleGlobal->HwErrVariableTotalSize = HwErrVariableTotalSize;
       mVariableModuleGlobal->CommonVariableTotalSize = CommonVariableTotalSize;
       mVariableModuleGlobal->CommonUserVariableTotalSize = CommonUserVariableTotalSize;
--
1.9.5.msysgit.0



^ permalink raw reply related	[flat|nested] 18+ messages in thread

end of thread, other threads:[~2017-03-06  1:37 UTC | newest]

Thread overview: 18+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2017-02-25  4:05 [PATCH v3 0/6] Refine type cast for pointer subtraction Hao Wu
2017-02-25  4:05 ` [PATCH v3 1/6] MdeModulePkg: " Hao Wu
2017-03-06  1:37   ` Tian, Feng
2017-02-25  4:05 ` [PATCH v3 2/6] CryptoPkg: " Hao Wu
2017-02-27  2:23   ` Long, Qin
2017-02-25  4:05 ` [PATCH v3 3/6] IntelFrameworkModulePkg: " Hao Wu
2017-02-27  6:59   ` Fan, Jeff
2017-02-25  4:05 ` [PATCH v3 4/6] NetworkPkg: " Hao Wu
2017-03-06  1:03   ` Fu, Siyuan
2017-03-06  1:14   ` Wu, Jiaxin
2017-02-25  4:05 ` [PATCH v3 5/6] SecurityPkg: " Hao Wu
2017-03-06  1:29   ` Zhang, Chao B
2017-02-25  4:05 ` [PATCH v3 6/6] ShellPkg: " Hao Wu
2017-02-27  5:10   ` Ni, Ruiyu
2017-02-27  5:59     ` Wu, Hao A
2017-02-27  7:06       ` Ni, Ruiyu
2017-02-27  7:18   ` Ni, Ruiyu
2017-02-27 16:38   ` Carsey, Jaben

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox