]> git.proxmox.com Git - mirror_edk2.git/blobdiff - SecurityPkg/VariableAuthenticated/RuntimeDxe/Variable.c
1. Update AuthVarialbe driver to avoid integer overflow when using EFI_VARIABLE_AUTHE...
[mirror_edk2.git] / SecurityPkg / VariableAuthenticated / RuntimeDxe / Variable.c
index df8b30a63e5f004c56de81495773bd1f3b2d0acf..c84a2f62d3d70c6aa43f7df96c41fac631b59004 100644 (file)
@@ -1,14 +1,14 @@
 /** @file\r
-  The common variable operation routines shared by DXE_RINTIME variable \r
+  The common variable operation routines shared by DXE_RINTIME variable\r
   module and DXE_SMM variable module.\r
 \r
-Copyright (c) 2009 - 2011, Intel Corporation. All rights reserved.<BR>\r
-This program and the accompanying materials \r
-are licensed and made available under the terms and conditions of the BSD License \r
-which accompanies this distribution.  The full text of the license may be found at \r
+Copyright (c) 2009 - 2012, Intel Corporation. All rights reserved.<BR>\r
+This program and the accompanying materials\r
+are licensed and made available under the terms and conditions of the BSD License\r
+which accompanies this distribution.  The full text of the license may be found at\r
 http://opensource.org/licenses/bsd-license.php\r
 \r
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, \r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
 \r
 **/\r
@@ -30,13 +30,13 @@ VARIABLE_INFO_ENTRY    *gVariableInfo    = NULL;
 \r
 \r
 /**\r
-  Routine used to track statistical information about variable usage. \r
+  Routine used to track statistical information about variable usage.\r
   The data is stored in the EFI system table so it can be accessed later.\r
-  VariableInfo.efi can dump out the table. Only Boot Services variable \r
+  VariableInfo.efi can dump out the table. Only Boot Services variable\r
   accesses are tracked by this code. The PcdVariableCollectStatistics\r
-  build flag controls if this feature is enabled. \r
+  build flag controls if this feature is enabled.\r
 \r
-  A read that hits in the cache will have Read and Cache true for \r
+  A read that hits in the cache will have Read and Cache true for\r
   the transaction. Data is allocated by this routine, but never\r
   freed.\r
 \r
@@ -84,7 +84,7 @@ UpdateVariableInfo (
       gVariableInfo->Volatile = Volatile;\r
     }\r
 \r
-    \r
+\r
     for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) {\r
       if (CompareGuid (VendorGuid, &Entry->VendorGuid)) {\r
         if (StrCmp (VariableName, Entry->Name) == 0) {\r
@@ -230,14 +230,14 @@ UpdateVariableStore (
     if ((DataPtr + DataSize) >= ((UINTN) ((UINT8 *) VolatileBase + VolatileBase->Size))) {\r
       return EFI_INVALID_PARAMETER;\r
     }\r
-    \r
+\r
     //\r
     // If Volatile Variable just do a simple mem copy.\r
-    //    \r
+    //\r
     CopyMem ((UINT8 *)(UINTN)DataPtr, Buffer, DataSize);\r
     return EFI_SUCCESS;\r
   }\r
-  \r
+\r
   //\r
   // If we are here we are dealing with Non-Volatile Variables.\r
   //\r
@@ -412,7 +412,7 @@ GetVariableDataPtr (
   )\r
 {\r
   UINTN Value;\r
-  \r
+\r
   //\r
   // Be careful about pad size for alignment.\r
   //\r
@@ -483,7 +483,7 @@ GetStartPointer (
 \r
   @param VarStoreHeader  Pointer to the Variable Store Header.\r
 \r
-  @return Pointer to the end of the variable storage area. \r
+  @return Pointer to the end of the variable storage area.\r
 \r
 **/\r
 VARIABLE_HEADER *\r
@@ -557,7 +557,7 @@ Reclaim (
 \r
   while (IsValidVariableHeader (Variable)) {\r
     NextVariable = GetNextVariablePtr (Variable);\r
-    if (Variable->State == VAR_ADDED || \r
+    if (Variable->State == VAR_ADDED ||\r
         Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
        ) {\r
       VariableSize = (UINTN) NextVariable - (UINTN) Variable;\r
@@ -568,9 +568,9 @@ Reclaim (
   }\r
 \r
   //\r
-  // Reserve the 1 Bytes with Oxff to identify the \r
-  // end of the variable buffer. \r
-  // \r
+  // Reserve the 1 Bytes with Oxff to identify the\r
+  // end of the variable buffer.\r
+  //\r
   MaximumBufferSize += 1;\r
   ValidBuffer = AllocatePool (MaximumBufferSize);\r
   if (ValidBuffer == NULL) {\r
@@ -587,7 +587,7 @@ Reclaim (
 \r
   //\r
   // Reinstall all ADDED variables as long as they are not identical to Updating Variable.\r
-  // \r
+  //\r
   Variable = GetStartPointer (VariableStoreHeader);\r
   while (IsValidVariableHeader (Variable)) {\r
     NextVariable = GetNextVariablePtr (Variable);\r
@@ -638,18 +638,18 @@ Reclaim (
 \r
   //\r
   // Reinstall all in delete transition variables.\r
-  // \r
+  //\r
   Variable      = GetStartPointer (VariableStoreHeader);\r
   while (IsValidVariableHeader (Variable)) {\r
     NextVariable = GetNextVariablePtr (Variable);\r
     if (Variable != UpdatingVariable && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
 \r
       //\r
-      // Buffer has cached all ADDED variable. \r
+      // Buffer has cached all ADDED variable.\r
       // Per IN_DELETED variable, we have to guarantee that\r
-      // no ADDED one in previous buffer. \r
-      // \r
-     \r
+      // no ADDED one in previous buffer.\r
+      //\r
+\r
       FoundAdded = FALSE;\r
       AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer);\r
       while (IsValidVariableHeader (AddedVariable)) {\r
@@ -715,6 +715,67 @@ Reclaim (
   return Status;\r
 }\r
 \r
+/**\r
+  Find the variable in the specified variable store.\r
+\r
+  @param  VariableName        Name of the variable to be found\r
+  @param  VendorGuid          Vendor GUID to be found.\r
+  @param  PtrTrack            Variable Track Pointer structure that contains Variable Information.\r
+\r
+  @retval  EFI_SUCCESS            Variable found successfully\r
+  @retval  EFI_NOT_FOUND          Variable not found\r
+**/\r
+EFI_STATUS\r
+FindVariableEx (\r
+  IN     CHAR16                  *VariableName,\r
+  IN     EFI_GUID                *VendorGuid,\r
+  IN OUT VARIABLE_POINTER_TRACK  *PtrTrack\r
+  )\r
+{\r
+  VARIABLE_HEADER                *InDeletedVariable;\r
+  VOID                           *Point;\r
+\r
+  //\r
+  // Find the variable by walk through HOB, volatile and non-volatile variable store.\r
+  //\r
+  InDeletedVariable  = NULL;\r
+\r
+  for ( PtrTrack->CurrPtr = PtrTrack->StartPtr\r
+      ; (PtrTrack->CurrPtr < PtrTrack->EndPtr) && IsValidVariableHeader (PtrTrack->CurrPtr)\r
+      ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr)\r
+      ) {\r
+    if (PtrTrack->CurrPtr->State == VAR_ADDED ||\r
+        PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
+       ) {\r
+      if (!AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {\r
+        if (VariableName[0] == 0) {\r
+          if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+            InDeletedVariable   = PtrTrack->CurrPtr;\r
+          } else {\r
+            return EFI_SUCCESS;\r
+          }\r
+        } else {\r
+          if (CompareGuid (VendorGuid, &PtrTrack->CurrPtr->VendorGuid)) {\r
+            Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr);\r
+\r
+            ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0);\r
+            if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) {\r
+              if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
+                InDeletedVariable     = PtrTrack->CurrPtr;\r
+              } else {\r
+                return EFI_SUCCESS;\r
+              }\r
+            }\r
+          }\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  PtrTrack->CurrPtr = InDeletedVariable;\r
+  return (PtrTrack->CurrPtr  == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS;\r
+}\r
+\r
 \r
 /**\r
   Finds variable in storage blocks of volatile and non-volatile storage areas.\r
@@ -746,89 +807,40 @@ FindVariable (
   IN  VARIABLE_GLOBAL         *Global\r
   )\r
 {\r
-  VARIABLE_HEADER         *Variable[2];\r
-  VARIABLE_HEADER         *InDeletedVariable;\r
-  VARIABLE_STORE_HEADER   *VariableStoreHeader[2];\r
-  UINTN                   InDeletedStorageIndex;\r
-  UINTN                   Index;\r
-  VOID                    *Point;\r
+  EFI_STATUS              Status;\r
+  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];\r
+  VARIABLE_STORE_TYPE     Type;\r
+\r
+  if (VariableName[0] != 0 && VendorGuid == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
 \r
   //\r
-  // 0: Volatile, 1: Non-Volatile.\r
+  // 0: Volatile, 1: HOB, 2: Non-Volatile.\r
   // The index and attributes mapping must be kept in this order as RuntimeServiceGetNextVariableName\r
   // make use of this mapping to implement search algorithm.\r
   //\r
-  VariableStoreHeader[0]  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase);\r
-  VariableStoreHeader[1]  = mNvVariableCache;\r
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) Global->VolatileVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) Global->HobVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;\r
 \r
   //\r
-  // Start Pointers for the variable.\r
-  // Actual Data Pointer where data can be written.\r
+  // Find the variable by walk through HOB, volatile and non-volatile variable store.\r
   //\r
-  Variable[0] = GetStartPointer (VariableStoreHeader[0]);\r
-  Variable[1] = GetStartPointer (VariableStoreHeader[1]);\r
-\r
-  if (VariableName[0] != 0 && VendorGuid == NULL) {\r
-    return EFI_INVALID_PARAMETER;\r
-  }\r
+  for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {\r
+    if (VariableStoreHeader[Type] == NULL) {\r
+      continue;\r
+    }\r
 \r
-  //\r
-  // Find the variable by walk through volatile and then non-volatile variable store.\r
-  //\r
-  InDeletedVariable     = NULL;\r
-  InDeletedStorageIndex = 0;\r
-  for (Index = 0; Index < 2; Index++) {\r
-    while ((Variable[Index] < GetEndPointer (VariableStoreHeader[Index])) && IsValidVariableHeader (Variable[Index])) {\r
-      if (Variable[Index]->State == VAR_ADDED || \r
-          Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)\r
-         ) {\r
-        if (!AtRuntime () || ((Variable[Index]->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) {\r
-          if (VariableName[0] == 0) {\r
-            if (Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
-              InDeletedVariable     = Variable[Index];\r
-              InDeletedStorageIndex = Index;\r
-            } else {\r
-              PtrTrack->StartPtr  = GetStartPointer (VariableStoreHeader[Index]);\r
-              PtrTrack->EndPtr    = GetEndPointer (VariableStoreHeader[Index]);\r
-              PtrTrack->CurrPtr   = Variable[Index];\r
-              PtrTrack->Volatile  = (BOOLEAN)(Index == 0);\r
-\r
-              return EFI_SUCCESS;\r
-            }\r
-          } else {\r
-            if (CompareGuid (VendorGuid, &Variable[Index]->VendorGuid)) {\r
-              Point = (VOID *) GetVariableNamePtr (Variable[Index]);\r
-\r
-              ASSERT (NameSizeOfVariable (Variable[Index]) != 0);\r
-              if (CompareMem (VariableName, Point, NameSizeOfVariable (Variable[Index])) == 0) {\r
-                if (Variable[Index]->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) {\r
-                  InDeletedVariable     = Variable[Index];\r
-                  InDeletedStorageIndex = Index;\r
-                } else {\r
-                  PtrTrack->StartPtr  = GetStartPointer (VariableStoreHeader[Index]);\r
-                  PtrTrack->EndPtr    = GetEndPointer (VariableStoreHeader[Index]);\r
-                  PtrTrack->CurrPtr   = Variable[Index];\r
-                  PtrTrack->Volatile  = (BOOLEAN)(Index == 0);\r
-\r
-                  return EFI_SUCCESS;\r
-                }\r
-              }\r
-            }\r
-          }\r
-        }\r
-      }\r
+    PtrTrack->StartPtr = GetStartPointer (VariableStoreHeader[Type]);\r
+    PtrTrack->EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);\r
+    PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile);\r
 \r
-      Variable[Index] = GetNextVariablePtr (Variable[Index]);\r
-    }\r
-    if (InDeletedVariable != NULL) {\r
-      PtrTrack->StartPtr  = GetStartPointer (VariableStoreHeader[InDeletedStorageIndex]);\r
-      PtrTrack->EndPtr    = GetEndPointer (VariableStoreHeader[InDeletedStorageIndex]);\r
-      PtrTrack->CurrPtr   = InDeletedVariable;\r
-      PtrTrack->Volatile  = (BOOLEAN)(InDeletedStorageIndex == 0);\r
-      return EFI_SUCCESS;\r
+    Status = FindVariableEx (VariableName, VendorGuid, PtrTrack);\r
+    if (!EFI_ERROR (Status)) {\r
+      return Status;\r
     }\r
   }\r
-  PtrTrack->CurrPtr = NULL;\r
   return EFI_NOT_FOUND;\r
 }\r
 \r
@@ -863,7 +875,7 @@ GetIndexFromSupportedLangCodes(
   IN  CHAR8            *SupportedLang,\r
   IN  CHAR8            *Lang,\r
   IN  BOOLEAN          Iso639Language\r
-  ) \r
+  )\r
 {\r
   UINTN    Index;\r
   UINTN    CompareLength;\r
@@ -898,8 +910,8 @@ GetIndexFromSupportedLangCodes(
       // Determine the length of the next language code in SupportedLang\r
       //\r
       for (CompareLength = 0; SupportedLang[CompareLength] != '\0' && SupportedLang[CompareLength] != ';'; CompareLength++);\r
-      \r
-      if ((CompareLength == LanguageLength) && \r
+\r
+      if ((CompareLength == LanguageLength) &&\r
           (AsciiStrnCmp (Lang, SupportedLang, CompareLength) == 0)) {\r
         //\r
         // Successfully find the index of Lang string in SupportedLang string.\r
@@ -960,7 +972,7 @@ GetLangFromSupportedLangCodes (
     CompareLength = ISO_639_2_ENTRY_SIZE;\r
     mVariableModuleGlobal->Lang[CompareLength] = '\0';\r
     return CopyMem (mVariableModuleGlobal->Lang, SupportedLang + Index * CompareLength, CompareLength);\r
-      \r
+\r
   } else {\r
     while (TRUE) {\r
       //\r
@@ -997,10 +1009,10 @@ GetLangFromSupportedLangCodes (
 }\r
 \r
 /**\r
-  Returns a pointer to an allocated buffer that contains the best matching language \r
-  from a set of supported languages.  \r
-  \r
-  This function supports both ISO 639-2 and RFC 4646 language codes, but language \r
+  Returns a pointer to an allocated buffer that contains the best matching language\r
+  from a set of supported languages.\r
+\r
+  This function supports both ISO 639-2 and RFC 4646 language codes, but language\r
   code types may not be mixed in a single call to this function. This function\r
   supports a variable argument list that allows the caller to pass in a prioritized\r
   list of language codes to test against all the language codes in SupportedLanguages.\r
@@ -1008,37 +1020,37 @@ GetLangFromSupportedLangCodes (
   If SupportedLanguages is NULL, then ASSERT().\r
 \r
   @param[in]  SupportedLanguages  A pointer to a Null-terminated ASCII string that\r
-                                  contains a set of language codes in the format \r
+                                  contains a set of language codes in the format\r
                                   specified by Iso639Language.\r
   @param[in]  Iso639Language      If TRUE, then all language codes are assumed to be\r
                                   in ISO 639-2 format.  If FALSE, then all language\r
                                   codes are assumed to be in RFC 4646 language format\r
-  @param[in]  ...                 A variable argument list that contains pointers to \r
+  @param[in]  ...                 A variable argument list that contains pointers to\r
                                   Null-terminated ASCII strings that contain one or more\r
                                   language codes in the format specified by Iso639Language.\r
                                   The first language code from each of these language\r
                                   code lists is used to determine if it is an exact or\r
-                                  close match to any of the language codes in \r
+                                  close match to any of the language codes in\r
                                   SupportedLanguages.  Close matches only apply to RFC 4646\r
                                   language codes, and the matching algorithm from RFC 4647\r
-                                  is used to determine if a close match is present.  If \r
+                                  is used to determine if a close match is present.  If\r
                                   an exact or close match is found, then the matching\r
                                   language code from SupportedLanguages is returned.  If\r
                                   no matches are found, then the next variable argument\r
-                                  parameter is evaluated.  The variable argument list \r
+                                  parameter is evaluated.  The variable argument list\r
                                   is terminated by a NULL.\r
 \r
   @retval NULL   The best matching language could not be found in SupportedLanguages.\r
-  @retval NULL   There are not enough resources available to return the best matching \r
+  @retval NULL   There are not enough resources available to return the best matching\r
                  language.\r
-  @retval Other  A pointer to a Null-terminated ASCII string that is the best matching \r
+  @retval Other  A pointer to a Null-terminated ASCII string that is the best matching\r
                  language in SupportedLanguages.\r
 \r
 **/\r
 CHAR8 *\r
 EFIAPI\r
 VariableGetBestLanguage (\r
-  IN CONST CHAR8  *SupportedLanguages, \r
+  IN CONST CHAR8  *SupportedLanguages,\r
   IN BOOLEAN      Iso639Language,\r
   ...\r
   )\r
@@ -1115,7 +1127,7 @@ VariableGetBestLanguage (
         LanguageLength = 0;\r
       } else {\r
         //\r
-        // If RFC 4646 mode, then trim Language from the right to the next '-' character \r
+        // If RFC 4646 mode, then trim Language from the right to the next '-' character\r
         //\r
         for (LanguageLength--; LanguageLength > 0 && Language[LanguageLength] != '-'; LanguageLength--);\r
       }\r
@@ -1124,7 +1136,7 @@ VariableGetBestLanguage (
   VA_END (Args);\r
 \r
   //\r
-  // No matches were found \r
+  // No matches were found\r
   //\r
   return NULL;\r
 }\r
@@ -1145,7 +1157,7 @@ VariableGetBestLanguage (
 \r
 **/\r
 VOID\r
-AutoUpdateLangVariable(\r
+AutoUpdateLangVariable (\r
   IN  CHAR16             *VariableName,\r
   IN  VOID               *Data,\r
   IN  UINTN              DataSize\r
@@ -1189,7 +1201,7 @@ AutoUpdateLangVariable(
     ASSERT (mVariableModuleGlobal->PlatformLangCodes != NULL);\r
 \r
     //\r
-    // PlatformLang holds a single language from PlatformLangCodes, \r
+    // PlatformLang holds a single language from PlatformLangCodes,\r
     // so the size of PlatformLangCodes is enough for the PlatformLang.\r
     //\r
     if (mVariableModuleGlobal->PlatformLang != NULL) {\r
@@ -1219,14 +1231,14 @@ AutoUpdateLangVariable(
     ASSERT (mVariableModuleGlobal->LangCodes != NULL);\r
   }\r
 \r
-  if (SetLanguageCodes \r
+  if (SetLanguageCodes\r
       && (mVariableModuleGlobal->PlatformLangCodes != NULL)\r
       && (mVariableModuleGlobal->LangCodes != NULL)) {\r
     //\r
     // Update Lang if PlatformLang is already set\r
     // Update PlatformLang if Lang is already set\r
     //\r
-    Status = FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *) mVariableModuleGlobal);\r
+    Status = FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
     if (!EFI_ERROR (Status)) {\r
       //\r
       // Update Lang\r
@@ -1235,7 +1247,7 @@ AutoUpdateLangVariable(
       Data         = GetVariableDataPtr (Variable.CurrPtr);\r
       DataSize     = Variable.CurrPtr->DataSize;\r
     } else {\r
-      Status = FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *) mVariableModuleGlobal);\r
+      Status = FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
       if (!EFI_ERROR (Status)) {\r
         //\r
         // Update PlatformLang\r
@@ -1251,7 +1263,7 @@ AutoUpdateLangVariable(
       }\r
     }\r
   }\r
-  \r
+\r
   //\r
   // According to UEFI spec, "Lang" and "PlatformLang" is NV|BS|RT attributions.\r
   //\r
@@ -1280,7 +1292,7 @@ AutoUpdateLangVariable(
         //\r
         // Successfully convert PlatformLang to Lang, and set the BestLang value into Lang variable simultaneously.\r
         //\r
-        FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *)mVariableModuleGlobal);\r
+        FindVariable (L"Lang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
 \r
         Status = UpdateVariable (L"Lang", &gEfiGlobalVariableGuid, BestLang,\r
                                  ISO_639_2_ENTRY_SIZE + 1, Attributes, 0, 0, &Variable, NULL);\r
@@ -1314,9 +1326,9 @@ AutoUpdateLangVariable(
         //\r
         // Successfully convert Lang to PlatformLang, and set the BestPlatformLang value into PlatformLang variable simultaneously.\r
         //\r
-        FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, (VARIABLE_GLOBAL *)mVariableModuleGlobal);\r
+        FindVariable (L"PlatformLang", &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
 \r
-        Status = UpdateVariable (L"PlatformLang", &gEfiGlobalVariableGuid, BestPlatformLang, \r
+        Status = UpdateVariable (L"PlatformLang", &gEfiGlobalVariableGuid, BestPlatformLang,\r
                                  AsciiStrSize (BestPlatformLang), Attributes, 0, 0, &Variable, NULL);\r
 \r
         DEBUG ((EFI_D_INFO, "Variable Driver Auto Update Lang, Lang:%a, PlatformLang:%a\n", BestLang, BestPlatformLang));\r
@@ -1339,7 +1351,7 @@ AutoUpdateLangVariable(
   @param[in] MonotonicCount     Value of associated monotonic count.\r
   @param[in] CacheVariable      The variable information which is used to keep track of variable usage.\r
   @param[in] TimeStamp          Value of associated TimeStamp.\r
-  \r
+\r
   @retval EFI_SUCCESS           The update operation is success.\r
   @retval EFI_OUT_OF_RESOURCES  Variable region is full, can not write other data into this region.\r
 \r
@@ -1405,12 +1417,12 @@ UpdateVariable (
     // Now let Variable points to the same variable in Flash area.\r
     //\r
     VariableStoreHeader  = (VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
-    Variable = &NvVariable;    \r
+    Variable = &NvVariable;\r
     Variable->StartPtr = GetStartPointer (VariableStoreHeader);\r
     Variable->EndPtr   = GetEndPointer (VariableStoreHeader);\r
     Variable->CurrPtr  = (VARIABLE_HEADER *)((UINTN)Variable->StartPtr + ((UINTN)CacheVariable->CurrPtr - (UINTN)CacheVariable->StartPtr));\r
     Variable->Volatile = FALSE;\r
-  } \r
+  }\r
 \r
   Fvb       = mVariableModuleGlobal->FvbInstance;\r
   Reclaimed = FALSE;\r
@@ -1427,10 +1439,10 @@ UpdateVariable (
     //\r
     // Update/Delete existing variable.\r
     //\r
-    if (AtRuntime ()) {        \r
+    if (AtRuntime ()) {\r
       //\r
-      // If AtRuntime and the variable is Volatile and Runtime Access,  \r
-      // the volatile is ReadOnly, and SetVariable should be aborted and \r
+      // If AtRuntime and the variable is Volatile and Runtime Access,\r
+      // the volatile is ReadOnly, and SetVariable should be aborted and\r
       // return EFI_WRITE_PROTECTED.\r
       //\r
       if (Variable->Volatile) {\r
@@ -1442,17 +1454,17 @@ UpdateVariable (
       //\r
       if ((Variable->CurrPtr->Attributes & EFI_VARIABLE_NON_VOLATILE) == 0) {\r
         Status = EFI_INVALID_PARAMETER;\r
-        goto Done;      \r
+        goto Done;\r
       }\r
     }\r
 \r
     //\r
     // Setting a data variable with no access, or zero DataSize attributes\r
     // causes it to be deleted.\r
-    // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will \r
-    // not delete the variable.    \r
+    // When the EFI_VARIABLE_APPEND_WRITE attribute is set, DataSize of zero will\r
+    // not delete the variable.\r
     //\r
-    if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {    \r
+    if ((((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (DataSize == 0))|| ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0)) {\r
       State = Variable->CurrPtr->State;\r
       State &= VAR_DELETED;\r
 \r
@@ -1464,14 +1476,14 @@ UpdateVariable (
                  (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
-                 ); \r
+                 );\r
       if (!EFI_ERROR (Status)) {\r
         UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE);\r
         if (!Variable->Volatile) {\r
           CacheVariable->CurrPtr->State = State;\r
         }\r
       }\r
-      goto Done;     \r
+      goto Done;\r
     }\r
     //\r
     // If the variable is marked valid, and the same data has been passed in,\r
@@ -1479,8 +1491,11 @@ UpdateVariable (
     //\r
     if (DataSizeOfVariable (Variable->CurrPtr) == DataSize &&\r
         (CompareMem (Data, GetVariableDataPtr (Variable->CurrPtr), DataSize) == 0)  &&\r
-        ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0)) {\r
-      \r
+        ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) &&\r
+        (TimeStamp == NULL)) {\r
+      //\r
+      // Variable content unchanged and no need to update timestamp, just return.\r
+      //\r
       UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);\r
       Status = EFI_SUCCESS;\r
       goto Done;\r
@@ -1491,10 +1506,40 @@ UpdateVariable (
       // EFI_VARIABLE_APPEND_WRITE attribute only effects for existing variable\r
       //\r
       if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {\r
-    \r
-        BufSize = Variable->CurrPtr->DataSize +  DataSize;\r
-        RevBufSize = MIN (PcdGet32 (PcdMaxAppendVariableSize), ScratchDataSize);\r
-    \r
+        //\r
+        // Cache the previous variable data into StorageArea.\r
+        //\r
+        DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);\r
+        CopyMem (mStorageArea, (UINT8*)((UINTN) Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);\r
+\r
+        if (CompareGuid (VendorGuid, &gEfiImageSecurityDatabaseGuid) ||\r
+               (CompareGuid (VendorGuid, &gEfiGlobalVariableGuid) && (StrCmp (VariableName, EFI_KEY_EXCHANGE_KEY_NAME) == 0))) {\r
+          //\r
+          // For variables with the GUID EFI_IMAGE_SECURITY_DATABASE_GUID (i.e. where the data\r
+          // buffer is formatted as EFI_SIGNATURE_LIST), the driver shall not perform an append of\r
+          // EFI_SIGNATURE_DATA values that are already part of the existing variable value.\r
+          //\r
+          BufSize = AppendSignatureList (mStorageArea, Variable->CurrPtr->DataSize, Data, DataSize);\r
+          if (BufSize == Variable->CurrPtr->DataSize) {\r
+            if ((TimeStamp == NULL) || CompareTimeStamp (TimeStamp, &Variable->CurrPtr->TimeStamp)) {\r
+              //\r
+              // New EFI_SIGNATURE_DATA is not found and timestamp is not later\r
+              // than current timestamp, return EFI_SUCCESS directly.\r
+              //\r
+              UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE);\r
+              Status = EFI_SUCCESS;\r
+              goto Done;\r
+            }\r
+          }\r
+        } else {\r
+          //\r
+          // For other Variables, append the new data to the end of previous data.\r
+          //\r
+          CopyMem ((UINT8*)((UINTN) mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize);\r
+          BufSize = Variable->CurrPtr->DataSize + DataSize;\r
+        }\r
+\r
+        RevBufSize = MIN (PcdGet32 (PcdMaxVariableSize), ScratchDataSize);\r
         if (BufSize > RevBufSize) {\r
           //\r
           // If variable size (previous + current) is bigger than reserved buffer in runtime,\r
@@ -1502,19 +1547,7 @@ UpdateVariable (
           //\r
           return EFI_OUT_OF_RESOURCES;\r
         }\r
-       \r
-        SetMem (mStorageArea, PcdGet32 (PcdMaxAppendVariableSize), 0xff);\r
-        //\r
-        // Cache the previous variable data into StorageArea.\r
-        //\r
-        DataOffset = sizeof (VARIABLE_HEADER) + Variable->CurrPtr->NameSize + GET_PAD_SIZE (Variable->CurrPtr->NameSize);\r
-        CopyMem (mStorageArea, (UINT8*)((UINTN)Variable->CurrPtr + DataOffset), Variable->CurrPtr->DataSize);\r
-        \r
-        //\r
-        // Append the new data to the end of previous data.\r
-        // \r
-        CopyMem ((UINT8*)((UINTN)mStorageArea + Variable->CurrPtr->DataSize), Data, DataSize);\r
-    \r
+\r
         //\r
         // Override Data and DataSize which are used for combined data area including previous and new data.\r
         //\r
@@ -1536,36 +1569,33 @@ UpdateVariable (
                  (UINTN) &Variable->CurrPtr->State,\r
                  sizeof (UINT8),\r
                  &State\r
-                 );      \r
+                 );\r
       if (EFI_ERROR (Status)) {\r
-        goto Done;  \r
-      } \r
+        goto Done;\r
+      }\r
       if (!Variable->Volatile) {\r
         CacheVariable->CurrPtr->State = State;\r
       }\r
-    }    \r
+    }\r
   } else {\r
     //\r
     // Not found existing variable. Create a new variable.\r
-    //  \r
-\r
     //\r
-    // EFI_VARIABLE_APPEND_WRITE attribute only set for existing variable\r
-    //\r
-    if ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) {\r
-      Status = EFI_INVALID_PARAMETER;\r
+\r
+    if ((DataSize == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0)) {\r
+      Status = EFI_SUCCESS;\r
       goto Done;\r
     }\r
-    \r
+\r
     //\r
     // Make sure we are trying to create a new variable.\r
-    // Setting a data variable with zero DataSize or no access attributes means to delete it.    \r
+    // Setting a data variable with zero DataSize or no access attributes means to delete it.\r
     //\r
     if (DataSize == 0 || (Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == 0) {\r
       Status = EFI_NOT_FOUND;\r
       goto Done;\r
     }\r
-        \r
+\r
     //\r
     // Only variable have NV|RT attribute can be created in Runtime.\r
     //\r
@@ -1573,7 +1603,7 @@ UpdateVariable (
         (((Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0) || ((Attributes & EFI_VARIABLE_NON_VOLATILE) == 0))) {\r
       Status = EFI_INVALID_PARAMETER;\r
       goto Done;\r
-    }         \r
+    }\r
   }\r
 \r
   //\r
@@ -1589,30 +1619,32 @@ UpdateVariable (
   NextVariable->Reserved        = 0;\r
   NextVariable->PubKeyIndex     = KeyIndex;\r
   NextVariable->MonotonicCount  = MonotonicCount;\r
-  SetMem (&NextVariable->TimeStamp, sizeof (EFI_TIME), 0);\r
-\r
-  if (((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && \r
-      ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) {\r
-    CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));\r
-  } else if (\r
-      ((Attributes & EFI_VARIABLE_APPEND_WRITE) != 0) && \r
-      ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0)) {\r
+  ZeroMem (&NextVariable->TimeStamp, sizeof (EFI_TIME));\r
+\r
+  if (((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) &&\r
+      (TimeStamp != NULL)) {\r
+    if ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) {\r
+      CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));\r
+    } else {\r
       //\r
       // In the case when the EFI_VARIABLE_APPEND_WRITE attribute is set, only\r
       // when the new TimeStamp value is later than the current timestamp associated\r
       // with the variable, we need associate the new timestamp with the updated value.\r
       //\r
-      if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) {\r
-        CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));\r
+      if (Variable->CurrPtr != NULL) {\r
+        if (CompareTimeStamp (&Variable->CurrPtr->TimeStamp, TimeStamp)) {\r
+          CopyMem (&NextVariable->TimeStamp, TimeStamp, sizeof (EFI_TIME));\r
+        }\r
       }\r
+    }\r
   }\r
 \r
   //\r
-  // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned \r
+  // The EFI_VARIABLE_APPEND_WRITE attribute will never be set in the returned\r
   // Attributes bitmask parameter of a GetVariable() call.\r
   //\r
   NextVariable->Attributes  = Attributes & (~EFI_VARIABLE_APPEND_WRITE);\r
-  \r
+\r
   VarNameOffset                 = sizeof (VARIABLE_HEADER);\r
   VarNameSize                   = StrSize (VariableName);\r
   CopyMem (\r
@@ -1646,9 +1678,9 @@ UpdateVariable (
     //\r
     Volatile = FALSE;\r
     NonVolatileVarableStoreSize = ((VARIABLE_STORE_HEADER *)(UINTN)(mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase))->Size;\r
-    if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) \r
+    if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)\r
       && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))\r
-      || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) \r
+      || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)\r
       && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {\r
       if (AtRuntime ()) {\r
         Status = EFI_OUT_OF_RESOURCES;\r
@@ -1657,7 +1689,7 @@ UpdateVariable (
       //\r
       // Perform garbage collection & reclaim operation.\r
       //\r
-      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, \r
+      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
                         &mVariableModuleGlobal->NonVolatileLastVariableOffset, FALSE, Variable->CurrPtr);\r
       if (EFI_ERROR (Status)) {\r
         goto Done;\r
@@ -1665,9 +1697,9 @@ UpdateVariable (
       //\r
       // If still no enough space, return out of resources.\r
       //\r
-      if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0) \r
+      if ((((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != 0)\r
         && ((VarSize + mVariableModuleGlobal->HwErrVariableTotalSize) > PcdGet32 (PcdHwErrStorageSize)))\r
-        || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0) \r
+        || (((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == 0)\r
         && ((VarSize + mVariableModuleGlobal->CommonVariableTotalSize) > NonVolatileVarableStoreSize - sizeof (VARIABLE_STORE_HEADER) - PcdGet32 (PcdHwErrStorageSize)))) {\r
         Status = EFI_OUT_OF_RESOURCES;\r
         goto Done;\r
@@ -1677,7 +1709,7 @@ UpdateVariable (
     //\r
     // Four steps\r
     // 1. Write variable header\r
-    // 2. Set variable state to header valid  \r
+    // 2. Set variable state to header valid\r
     // 3. Write variable data\r
     // 4. Set variable state to valid\r
     //\r
@@ -1764,7 +1796,7 @@ UpdateVariable (
   } else {\r
     //\r
     // Create a volatile variable.\r
-    //      \r
+    //\r
     Volatile = TRUE;\r
 \r
     if ((UINT32) (VarSize + mVariableModuleGlobal->VolatileLastVariableOffset) >\r
@@ -1772,7 +1804,7 @@ UpdateVariable (
       //\r
       // Perform garbage collection & reclaim operation.\r
       //\r
-      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase, \r
+      Status = Reclaim (mVariableModuleGlobal->VariableGlobal.VolatileVariableBase,\r
                           &mVariableModuleGlobal->VolatileLastVariableOffset, TRUE, Variable->CurrPtr);\r
       if (EFI_ERROR (Status)) {\r
         goto Done;\r
@@ -1823,7 +1855,7 @@ UpdateVariable (
              sizeof (UINT8),\r
              &State\r
              );\r
-    if (!EFI_ERROR (Status) && !Variable->Volatile) {         \r
+    if (!EFI_ERROR (Status) && !Variable->Volatile) {\r
       CacheVariable->CurrPtr->State = State;\r
     }\r
   }\r
@@ -1846,7 +1878,7 @@ Done:
   @param DataSize                   Size of Data found. If size is less than the\r
                                     data, this value contains the required size.\r
   @param Data                       Data pointer.\r
-                      \r
+\r
   @return EFI_INVALID_PARAMETER     Invalid parameter.\r
   @return EFI_SUCCESS               Find the specified variable.\r
   @return EFI_NOT_FOUND             Not found.\r
@@ -1872,7 +1904,7 @@ VariableServiceGetVariable (
   }\r
 \r
   AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
-  \r
+\r
   Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal);\r
   if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) {\r
     goto Done;\r
@@ -1897,7 +1929,7 @@ VariableServiceGetVariable (
 \r
     *DataSize = VarDataSize;\r
     UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE);\r
\r
+\r
     Status = EFI_SUCCESS;\r
     goto Done;\r
   } else {\r
@@ -1935,9 +1967,12 @@ VariableServiceGetNextVariableName (
   IN OUT  EFI_GUID          *VendorGuid\r
   )\r
 {\r
+  VARIABLE_STORE_TYPE     Type;\r
   VARIABLE_POINTER_TRACK  Variable;\r
+  VARIABLE_POINTER_TRACK  VariableInHob;\r
   UINTN                   VarNameSize;\r
   EFI_STATUS              Status;\r
+  VARIABLE_STORE_HEADER   *VariableStoreHeader[VariableStoreTypeMax];\r
 \r
   if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
@@ -1957,45 +1992,85 @@ VariableServiceGetNextVariableName (
     Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
   }\r
 \r
+  //\r
+  // 0: Volatile, 1: HOB, 2: Non-Volatile.\r
+  // The index and attributes mapping must be kept in this order as FindVariable\r
+  // makes use of this mapping to implement search algorithm.\r
+  //\r
+  VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeHob]      = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;\r
+  VariableStoreHeader[VariableStoreTypeNv]       = mNvVariableCache;\r
+\r
   while (TRUE) {\r
     //\r
-    // If both volatile and non-volatile variable store are parsed,\r
-    // return not found.\r
+    // Switch from Volatile to HOB, to Non-Volatile.\r
     //\r
-    if (Variable.CurrPtr >= Variable.EndPtr || Variable.CurrPtr == NULL) {\r
-      Variable.Volatile = (BOOLEAN) (Variable.Volatile ^ ((BOOLEAN) 0x1));\r
-      if (!Variable.Volatile) {\r
-        Variable.StartPtr = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase);\r
-        Variable.EndPtr   = GetEndPointer ((VARIABLE_STORE_HEADER *) ((UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase));\r
-      } else {\r
+    while ((Variable.CurrPtr >= Variable.EndPtr) ||\r
+           (Variable.CurrPtr == NULL)            ||\r
+           !IsValidVariableHeader (Variable.CurrPtr)\r
+          ) {\r
+      //\r
+      // Find current storage index\r
+      //\r
+      for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) {\r
+        if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) {\r
+          break;\r
+        }\r
+      }\r
+      ASSERT (Type < VariableStoreTypeMax);\r
+      //\r
+      // Switch to next storage\r
+      //\r
+      for (Type++; Type < VariableStoreTypeMax; Type++) {\r
+        if (VariableStoreHeader[Type] != NULL) {\r
+          break;\r
+        }\r
+      }\r
+      //\r
+      // Capture the case that\r
+      // 1. current storage is the last one, or\r
+      // 2. no further storage\r
+      //\r
+      if (Type == VariableStoreTypeMax) {\r
         Status = EFI_NOT_FOUND;\r
         goto Done;\r
       }\r
-\r
-      Variable.CurrPtr = Variable.StartPtr;\r
-      if (!IsValidVariableHeader (Variable.CurrPtr)) {\r
-        continue;\r
-      }\r
+      Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]);\r
+      Variable.EndPtr   = GetEndPointer   (VariableStoreHeader[Type]);\r
+      Variable.CurrPtr  = Variable.StartPtr;\r
     }\r
+\r
     //\r
     // Variable is found\r
     //\r
-    if (IsValidVariableHeader (Variable.CurrPtr) && Variable.CurrPtr->State == VAR_ADDED) {\r
+    if (Variable.CurrPtr->State == VAR_ADDED) {\r
       if ((AtRuntime () && ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) == 0)) == 0) {\r
+\r
+        //\r
+        // Don't return NV variable when HOB overrides it\r
+        //\r
+        if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) &&\r
+            (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv]))\r
+           ) {\r
+          VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]);\r
+          VariableInHob.EndPtr   = GetEndPointer   (VariableStoreHeader[VariableStoreTypeHob]);\r
+          Status = FindVariableEx (\r
+                     GetVariableNamePtr (Variable.CurrPtr),\r
+                     &Variable.CurrPtr->VendorGuid,\r
+                     &VariableInHob\r
+                     );\r
+          if (!EFI_ERROR (Status)) {\r
+            Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr);\r
+            continue;\r
+          }\r
+        }\r
+\r
         VarNameSize = NameSizeOfVariable (Variable.CurrPtr);\r
         ASSERT (VarNameSize != 0);\r
 \r
         if (VarNameSize <= *VariableNameSize) {\r
-          CopyMem (\r
-            VariableName,\r
-            GetVariableNamePtr (Variable.CurrPtr),\r
-            VarNameSize\r
-            );\r
-          CopyMem (\r
-            VendorGuid,\r
-            &Variable.CurrPtr->VendorGuid,\r
-            sizeof (EFI_GUID)\r
-            );\r
+          CopyMem (VariableName, GetVariableNamePtr (Variable.CurrPtr), VarNameSize);\r
+          CopyMem (VendorGuid, &Variable.CurrPtr->VendorGuid, sizeof (EFI_GUID));\r
           Status = EFI_SUCCESS;\r
         } else {\r
           Status = EFI_BUFFER_TOO_SMALL;\r
@@ -2053,7 +2128,7 @@ VariableServiceSetVariable (
   //\r
   if (VariableName == NULL || VariableName[0] == 0 || VendorGuid == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
-  } \r
+  }\r
 \r
   if (DataSize != 0 && Data == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
@@ -2067,25 +2142,36 @@ VariableServiceSetVariable (
   }\r
 \r
   //\r
-  // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute \r
+  // EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS and EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute\r
   // cannot be set both.\r
   //\r
-  if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)             \\r
+  if (((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)\r
      && ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) {\r
     return EFI_INVALID_PARAMETER;\r
-  }  \r
+  }\r
 \r
   if ((Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) {\r
     if (DataSize < AUTHINFO_SIZE) {\r
       //\r
-      // Try to write Authencated Variable without AuthInfo.\r
+      // Try to write Authenticated Variable without AuthInfo.\r
       //\r
       return EFI_SECURITY_VIOLATION;\r
-    } \r
-    PayloadSize = DataSize - AUTHINFO_SIZE; \r
+    }\r
+    PayloadSize = DataSize - AUTHINFO_SIZE;\r
+  } else if ((Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) == EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) {\r
+    //\r
+    // Sanity check for EFI_VARIABLE_AUTHENTICATION_2 descriptor.\r
+    //\r
+    if (DataSize < OFFSET_OF_AUTHINFO2_CERT_DATA ||\r
+      ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength > DataSize - (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) ||\r
+      ((EFI_VARIABLE_AUTHENTICATION_2 *) Data)->AuthInfo.Hdr.dwLength < OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) {\r
+      return EFI_SECURITY_VIOLATION;\r
+    }\r
+    PayloadSize = DataSize - AUTHINFO2_SIZE (Data);\r
   } else {\r
-    PayloadSize = DataSize; \r
+    PayloadSize = DataSize;\r
   }\r
+\r
   //\r
   //  The size of the VariableName, including the Unicode Null in bytes plus\r
   //  the DataSize is limited to maximum size of PcdGet32 (PcdMaxHardwareErrorVariableSize)\r
@@ -2110,8 +2196,8 @@ VariableServiceSetVariable (
     if ((PayloadSize > PcdGet32 (PcdMaxVariableSize)) ||\r
         (sizeof (VARIABLE_HEADER) + StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxVariableSize))) {\r
       return EFI_INVALID_PARAMETER;\r
-    }  \r
-  }  \r
+    }\r
+  }\r
 \r
   AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock);\r
 \r
@@ -2124,7 +2210,7 @@ VariableServiceSetVariable (
     // Parse non-volatile variable data and get last variable offset.\r
     //\r
     NextVariable  = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point);\r
-    while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point)) \r
+    while ((NextVariable < GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))\r
         && IsValidVariableHeader (NextVariable)) {\r
       NextVariable = GetNextVariablePtr (NextVariable);\r
     }\r
@@ -2204,7 +2290,7 @@ VariableServiceQueryVariableInfo (
     //\r
     // Make sure the Attributes combination is supported by the platform.\r
     //\r
-    return EFI_UNSUPPORTED;  \r
+    return EFI_UNSUPPORTED;\r
   } else if ((Attributes & (EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_BOOTSERVICE_ACCESS)) == EFI_VARIABLE_RUNTIME_ACCESS) {\r
     //\r
     // Make sure if runtime bit is set, boot service bit is set also.\r
@@ -2323,7 +2409,7 @@ VariableServiceQueryVariableInfo (
 \r
 /**\r
   This function reclaims variable storage if free size is below the threshold.\r
-  \r
+\r
 **/\r
 VOID\r
 ReclaimForOS(\r
@@ -2335,7 +2421,7 @@ ReclaimForOS(
   UINTN                          RemainingCommonVariableSpace;\r
   UINTN                          RemainingHwErrVariableSpace;\r
 \r
-  Status  = EFI_SUCCESS; \r
+  Status  = EFI_SUCCESS;\r
 \r
   CommonVariableSpace = ((VARIABLE_STORE_HEADER *) ((UINTN) (mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase)))->Size - sizeof (VARIABLE_STORE_HEADER) - PcdGet32(PcdHwErrStorageSize); //Allowable max size of common variable storage space\r
 \r
@@ -2346,7 +2432,7 @@ ReclaimForOS(
   // Check if the free area is blow a threshold.\r
   //\r
   if ((RemainingCommonVariableSpace < PcdGet32 (PcdMaxVariableSize))\r
-    || ((PcdGet32 (PcdHwErrStorageSize) != 0) && \r
+    || ((PcdGet32 (PcdHwErrStorageSize) != 0) &&\r
        (RemainingHwErrVariableSpace < PcdGet32 (PcdMaxHardwareErrorVariableSize)))){\r
     Status = Reclaim (\r
             mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase,\r
@@ -2376,16 +2462,16 @@ VariableWriteServiceInitialize (
   UINTN                           Index;\r
   UINT8                           Data;\r
   EFI_PHYSICAL_ADDRESS            VariableStoreBase;\r
-  UINT64                          VariableStoreLength;\r
+  VARIABLE_HEADER                 *Variable;\r
+  VOID                            *VariableData;\r
 \r
   VariableStoreBase   = mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase;\r
   VariableStoreHeader = (VARIABLE_STORE_HEADER *)(UINTN)VariableStoreBase;\r
-  VariableStoreLength = VariableStoreHeader->Size;\r
-  \r
+\r
   //\r
   // Check if the free area is really free.\r
   //\r
-  for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreLength; Index++) {\r
+  for (Index = mVariableModuleGlobal->NonVolatileLastVariableOffset; Index < VariableStoreHeader->Size; Index++) {\r
     Data = ((UINT8 *) mNvVariableCache)[Index];\r
     if (Data != 0xff) {\r
       //\r
@@ -2404,6 +2490,35 @@ VariableWriteServiceInitialize (
     }\r
   }\r
 \r
+\r
+  //\r
+  // Flush the HOB variable to flash and invalidate HOB variable.\r
+  //\r
+  if (mVariableModuleGlobal->VariableGlobal.HobVariableBase != 0) {\r
+    //\r
+    // Clear the HobVariableBase to avoid SetVariable() updating the variable in HOB\r
+    //\r
+    VariableStoreHeader = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase;\r
+    mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0;\r
+\r
+    for ( Variable = GetStartPointer (VariableStoreHeader)\r
+        ; (Variable < GetEndPointer (VariableStoreHeader) && IsValidVariableHeader (Variable))\r
+        ; Variable = GetNextVariablePtr (Variable)\r
+        ) {\r
+      ASSERT (Variable->State == VAR_ADDED);\r
+      ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0);\r
+      VariableData = GetVariableDataPtr (Variable);\r
+      Status = VariableServiceSetVariable (\r
+                 GetVariableNamePtr (Variable),\r
+                 &Variable->VendorGuid,\r
+                 Variable->Attributes,\r
+                 Variable->DataSize,\r
+                 VariableData\r
+                 );\r
+      ASSERT_EFI_ERROR (Status);\r
+    }\r
+  }\r
+\r
   //\r
   // Authenticated variable initialize.\r
   //\r
@@ -2434,6 +2549,7 @@ VariableCommonInitialize (
   UINT64                          VariableStoreLength;\r
   UINTN                           ScratchSize;\r
   UINTN                           VariableSize;\r
+  EFI_HOB_GUID_TYPE               *GuidHob;\r
 \r
   //\r
   // Allocate runtime memory for variable driver global structure.\r
@@ -2448,11 +2564,24 @@ VariableCommonInitialize (
   //\r
   // Note that in EdkII variable driver implementation, Hardware Error Record type variable\r
   // is stored with common variable in the same NV region. So the platform integrator should\r
-  // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of \r
+  // ensure that the value of PcdHwErrStorageSize is less than or equal to the value of\r
   // PcdFlashNvStorageVariableSize.\r
   //\r
   ASSERT (PcdGet32 (PcdHwErrStorageSize) <= PcdGet32 (PcdFlashNvStorageVariableSize));\r
 \r
+  //\r
+  // Get HOB variable store.\r
+  //\r
+  GuidHob = GetFirstGuidHob (&gEfiAuthenticatedVariableGuid);\r
+  if (GuidHob != NULL) {\r
+    VariableStoreHeader = GET_GUID_HOB_DATA (GuidHob);\r
+    if (GetVariableStoreStatus (VariableStoreHeader) == EfiValid) {\r
+      mVariableModuleGlobal->VariableGlobal.HobVariableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStoreHeader;\r
+    } else {\r
+      DEBUG ((EFI_D_ERROR, "HOB Variable Store header is corrupted!\n"));\r
+    }\r
+  }\r
+\r
   //\r
   // Allocate memory for volatile variable store, note that there is a scratch space to store scratch data.\r
   //\r
@@ -2480,13 +2609,24 @@ VariableCommonInitialize (
   VolatileVariableStore->Reserved1   = 0;\r
 \r
   //\r
-  // Get non-volatile varaible store.\r
+  // Get non-volatile variable store.\r
   //\r
 \r
   TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageVariableBase64);\r
   if (TempVariableStoreHeader == 0) {\r
     TempVariableStoreHeader = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageVariableBase);\r
   }\r
+  \r
+  //\r
+  // Check if the Firmware Volume is not corrupted\r
+  //\r
+  if ((((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->Signature != EFI_FVH_SIGNATURE) ||\r
+      (!CompareGuid (&gEfiSystemNvDataFvGuid, &((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader))->FileSystemGuid))) {\r
+    Status = EFI_VOLUME_CORRUPTED;\r
+    DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n"));\r
+    goto Done;\r
+  }\r
+\r
   VariableStoreBase       = TempVariableStoreHeader + \\r
                               (((EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)(TempVariableStoreHeader)) -> HeaderLength);\r
   VariableStoreLength     = (UINT64) PcdGet32 (PcdFlashNvStorageVariableSize) - \\r
@@ -2498,9 +2638,9 @@ VariableCommonInitialize (
     Status = EFI_VOLUME_CORRUPTED;\r
     DEBUG((EFI_D_INFO, "Variable Store header is corrupted\n"));\r
     goto Done;\r
-  }  \r
+  }\r
   ASSERT(VariableStoreHeader->Size == VariableStoreLength);\r
-    \r
+\r
   //\r
   // Parse non-volatile variable data and get last variable offset.\r
   //\r
@@ -2517,7 +2657,7 @@ VariableCommonInitialize (
   }\r
 \r
   mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) VariableStoreBase;\r
-    \r
+\r
   //\r
   // Allocate runtime memory used for a memory copy of the FLASH region.\r
   // Keep the memory and the FLASH in sync as updates occur\r
@@ -2563,7 +2703,7 @@ GetFvbInfoByAddress (
   EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL      *Fvb;\r
   EFI_FIRMWARE_VOLUME_HEADER              *FwVolHeader;\r
   EFI_FVB_ATTRIBUTES_2                    Attributes;\r
\r
+\r
   //\r
   // Get all FVB handles.\r
   //\r
@@ -2588,9 +2728,9 @@ GetFvbInfoByAddress (
     //\r
     Status = Fvb->GetAttributes (Fvb, &Attributes);\r
     if (EFI_ERROR (Status) || ((Attributes & EFI_FVB2_WRITE_STATUS) == 0)) {\r
-      continue;     \r
+      continue;\r
     }\r
-    \r
+\r
     //\r
     // Compare the address and select the right one.\r
     //\r
@@ -2616,7 +2756,7 @@ GetFvbInfoByAddress (
   if (Fvb == NULL) {\r
     Status = EFI_NOT_FOUND;\r
   }\r
-  \r
-  return Status;  \r
+\r
+  return Status;\r
 }\r
 \r