]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Library/DxeNetLib/DxeNetLib.c
MdeModulePkg/DxeNetLib: Add array range check in NetIp6IsNetEqual().
[mirror_edk2.git] / MdeModulePkg / Library / DxeNetLib / DxeNetLib.c
index 7cd7e3aca007282871348d9819ff1837b86a741d..90d2e3e64d86d1608e3050ecb933d90dfa34ddb1 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   Network library.\r
 \r
-Copyright (c) 2005 - 2017, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2005 - 2018, Intel Corporation. All rights reserved.<BR>\r
 (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>\r
 This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
@@ -19,6 +19,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 #include <Protocol/DriverBinding.h>\r
 #include <Protocol/ServiceBinding.h>\r
 #include <Protocol/SimpleNetwork.h>\r
+#include <Protocol/AdapterInformation.h>\r
 #include <Protocol/ManagedNetwork.h>\r
 #include <Protocol/Ip4Config2.h>\r
 #include <Protocol/ComponentName.h>\r
@@ -37,7 +38,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 #include <Library/PrintLib.h>\r
 #include <Library/UefiLib.h>\r
 \r
-#define NIC_ITEM_CONFIG_SIZE   sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE\r
+#define NIC_ITEM_CONFIG_SIZE   (sizeof (NIC_IP4_CONFIG_INFO) + sizeof (EFI_IP4_ROUTE_TABLE) * MAX_IP4_CONFIG_IN_VARIABLE)\r
 #define DEFAULT_ZERO_START     ((UINTN) ~0)\r
 \r
 //\r
@@ -197,6 +198,7 @@ SyslogLocateSnp (
   fill in the source MAC because it will try to locate a SNP each\r
   time it is called to avoid the problem if SNP is unloaded.\r
   This code snip is copied from MNP.\r
+  If Packet is NULL, then ASSERT().\r
 \r
   @param[in] Packet          The Syslog packet\r
   @param[in] Length          The length of the packet\r
@@ -218,6 +220,8 @@ SyslogSendPacket (
   EFI_EVENT                   TimeoutEvent;\r
   UINT8                       *TxBuf;\r
 \r
+  ASSERT (Packet != NULL);\r
+\r
   Snp = SyslogLocateSnp ();\r
 \r
   if (Snp == NULL) {\r
@@ -309,7 +313,7 @@ ON_EXIT:
   @param[in]  BufLen    The lenght of the Buf\r
   @param[out] Buf       The buffer to put the packet data\r
 \r
-  @return The length of the syslog packet built.\r
+  @return The length of the syslog packet built, 0 represents no packet is built.\r
 \r
 **/\r
 UINT32\r
@@ -323,6 +327,7 @@ SyslogBuildPacket (
   OUT CHAR8                 *Buf\r
   )\r
 {\r
+  EFI_STATUS                Status;\r
   ETHER_HEAD                *Ether;\r
   IP4_HEAD                  *Ip4;\r
   EFI_UDP_HEADER            *Udp4;\r
@@ -378,8 +383,10 @@ SyslogBuildPacket (
   // Build the syslog message body with <PRI> Timestamp  machine module Message\r
   //\r
   Pri = ((NET_SYSLOG_FACILITY & 31) << 3) | (Level & 7);\r
-  gRT->GetTime (&Time, NULL);\r
-  ASSERT ((Time.Month <= 12) && (Time.Month >= 1));\r
+  Status = gRT->GetTime (&Time, NULL);\r
+  if (EFI_ERROR (Status)) {\r
+    return 0;\r
+  }\r
 \r
   //\r
   // Use %a to format the ASCII strings, %s to format UNICODE strings\r
@@ -396,7 +403,6 @@ SyslogBuildPacket (
                     Time.Minute,\r
                     Time.Second\r
                     );\r
-  Len--;\r
 \r
   Len += (UINT32) AsciiSPrint (\r
                     Buf + Len,\r
@@ -407,7 +413,7 @@ SyslogBuildPacket (
                     Line,\r
                     File\r
                     );\r
-  Len--;\r
+  Len ++;\r
 \r
   //\r
   // OK, patch the IP length/checksum and UDP length fields.\r
@@ -438,6 +444,8 @@ SyslogBuildPacket (
            NetDebugASPrint ("State transit to %a\n", Name)\r
          )\r
 \r
+  If Format is NULL, then ASSERT().\r
+\r
   @param Format  The ASCII format string.\r
   @param ...     The variable length parameter whose format is determined\r
                  by the Format string.\r
@@ -456,6 +464,8 @@ NetDebugASPrint (
   VA_LIST                   Marker;\r
   CHAR8                     *Buf;\r
 \r
+  ASSERT (Format != NULL);\r
+\r
   Buf = (CHAR8 *) AllocatePool (NET_DEBUG_MSG_LEN);\r
 \r
   if (Buf == NULL) {\r
@@ -482,7 +492,8 @@ NetDebugASPrint (
   @param Message  The user message to log.\r
 \r
   @retval EFI_INVALID_PARAMETER Any input parameter is invalid.\r
-  @retval EFI_OUT_OF_RESOURCES  Failed to allocate memory for the packet\r
+  @retval EFI_OUT_OF_RESOURCES  Failed to allocate memory for the packet.\r
+  @retval EFI_DEVICE_ERROR      Device error occurs.\r
   @retval EFI_SUCCESS           The log is discard because that it is more verbose\r
                                 than the mNetDebugLevelMax. Or, it has been sent out.\r
 **/\r
@@ -503,7 +514,7 @@ NetDebugOutput (
   //\r
   // Check whether the message should be sent out\r
   //\r
-  if (Message == NULL) {\r
+  if (Message == NULL || File == NULL || Module == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
@@ -536,9 +547,13 @@ NetDebugOutput (
           NET_SYSLOG_PACKET_LEN,\r
           Packet\r
           );\r
+  if (Len == 0) {\r
+    Status = EFI_DEVICE_ERROR;\r
+  } else {\r
+    mSyslogPacketSeq++;\r
+    Status = SyslogSendPacket (Packet, Len);\r
+  }\r
 \r
-  mSyslogPacketSeq++;\r
-  Status = SyslogSendPacket (Packet, Len);\r
   FreePool (Packet);\r
 \r
 ON_EXIT:\r
@@ -637,7 +652,9 @@ NetGetIpClass (
 \r
   ASSERT if NetMask is zero.\r
   \r
-  If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address.\r
+  If all bits of the host address of IP are 0 or 1, IP is also not a valid unicast address,\r
+  except when the originator is one of the endpoints of a point-to-point link with a 31-bit\r
+  mask (RFC3021).\r
 \r
   @param[in]  Ip                    The IP to check against.\r
   @param[in]  NetMask               The mask of the IP.\r
@@ -657,9 +674,13 @@ NetIp4IsUnicast (
   if (Ip == 0 || IP4_IS_LOCAL_BROADCAST (Ip)) {\r
     return FALSE;\r
   }\r
-  \r
-  if (((Ip &~NetMask) == ~NetMask) || ((Ip &~NetMask) == 0)) {\r
-    return FALSE;\r
+\r
+  if (NetGetMaskLength (NetMask) != 31) {\r
+    if (((Ip &~NetMask) == ~NetMask) || ((Ip &~NetMask) == 0)) {\r
+      return FALSE;\r
+    }\r
+  } else {\r
+    return TRUE;\r
   }\r
 \r
   return TRUE;\r
@@ -668,6 +689,8 @@ NetIp4IsUnicast (
 /**\r
   Check whether the incoming IPv6 address is a valid unicast address.\r
 \r
+  ASSERT if Ip6 is NULL.\r
+\r
   If the address is a multicast address has binary 0xFF at the start, it is not\r
   a valid unicast address. If the address is unspecified ::, it is not a valid\r
   unicast address to be assigned to any node. If the address is loopback address\r
@@ -688,6 +711,8 @@ NetIp6IsValidUnicast (
   UINT8 Byte;\r
   UINT8 Index;\r
 \r
+  ASSERT (Ip6 != NULL);\r
+\r
   if (Ip6->Addr[0] == 0xFF) {\r
     return FALSE;\r
   }\r
@@ -710,6 +735,8 @@ NetIp6IsValidUnicast (
 /**\r
   Check whether the incoming Ipv6 address is the unspecified address or not.\r
 \r
+  ASSERT if Ip6 is NULL.\r
+\r
   @param[in] Ip6   - Ip6 address, in network order.\r
 \r
   @retval TRUE     - Yes, unspecified\r
@@ -724,6 +751,8 @@ NetIp6IsUnspecifiedAddr (
 {\r
   UINT8 Index;\r
 \r
+  ASSERT (Ip6 != NULL);\r
+\r
   for (Index = 0; Index < 16; Index++) {\r
     if (Ip6->Addr[Index] != 0) {\r
       return FALSE;\r
@@ -736,6 +765,8 @@ NetIp6IsUnspecifiedAddr (
 /**\r
   Check whether the incoming Ipv6 address is a link-local address.\r
 \r
+  ASSERT if Ip6 is NULL.\r
+\r
   @param[in] Ip6   - Ip6 address, in network order.\r
 \r
   @retval TRUE  - Yes, link-local address\r
@@ -772,6 +803,9 @@ NetIp6IsLinkLocalAddr (
 /**\r
   Check whether the Ipv6 address1 and address2 are on the connected network.\r
 \r
+  ASSERT if Ip1 or Ip2 is NULL.\r
+  ASSERT if PrefixLength exceeds or equals to IP6_PREFIX_MAX.\r
+\r
   @param[in] Ip1          - Ip6 address1, in network order.\r
   @param[in] Ip2          - Ip6 address2, in network order.\r
   @param[in] PrefixLength - The prefix length of the checking net.\r
@@ -792,7 +826,7 @@ NetIp6IsNetEqual (
   UINT8 Bit;\r
   UINT8 Mask;\r
 \r
-  ASSERT ((Ip1 != NULL) && (Ip2 != NULL) && (PrefixLength <= IP6_PREFIX_MAX));\r
+  ASSERT ((Ip1 != NULL) && (Ip2 != NULL) && (PrefixLength < IP6_PREFIX_MAX));\r
 \r
   if (PrefixLength == 0) {\r
     return TRUE;\r
@@ -809,6 +843,9 @@ NetIp6IsNetEqual (
     Mask = (UINT8) (0xFF << (8 - Bit));\r
 \r
     ASSERT (Byte < 16);\r
+    if (Byte >= 16) {\r
+      return FALSE;\r
+    }\r
     if ((Ip1->Addr[Byte] & Mask) != (Ip2->Addr[Byte] & Mask)) {\r
       return FALSE;\r
     }\r
@@ -821,6 +858,8 @@ NetIp6IsNetEqual (
 /**\r
   Switches the endianess of an IPv6 address\r
 \r
+  ASSERT if Ip6 is NULL.\r
+\r
   This function swaps the bytes in a 128-bit IPv6 address to switch the value\r
   from little endian to big endian or vice versa. The byte swapped value is\r
   returned.\r
@@ -839,6 +878,8 @@ Ip6Swap128 (
   UINT64 High;\r
   UINT64 Low;\r
 \r
+  ASSERT (Ip6 != NULL);\r
+\r
   CopyMem (&High, Ip6, sizeof (UINT64));\r
   CopyMem (&Low, &Ip6->Addr[8], sizeof (UINT64));\r
 \r
@@ -872,7 +913,7 @@ NetRandomInitSeed (
   UINT64                    MonotonicCount;\r
 \r
   gRT->GetTime (&Time, NULL);\r
-  Seed = (~Time.Hour << 24 | Time.Day << 16 | Time.Minute << 8 | Time.Second);\r
+  Seed = (Time.Hour << 24 | Time.Day << 16 | Time.Minute << 8 | Time.Second);\r
   Seed ^= Time.Nanosecond;\r
   Seed ^= Time.Year << 7;\r
 \r
@@ -886,6 +927,8 @@ NetRandomInitSeed (
 /**\r
   Extract a UINT32 from a byte stream.\r
 \r
+  ASSERT if Buf is NULL.\r
+\r
   Copy a UINT32 from a byte stream, then converts it from Network\r
   byte order to host byte order. Use this function to avoid alignment error.\r
 \r
@@ -902,6 +945,8 @@ NetGetUint32 (
 {\r
   UINT32                    Value;\r
 \r
+  ASSERT (Buf != NULL);\r
+\r
   CopyMem (&Value, Buf, sizeof (UINT32));\r
   return NTOHL (Value);\r
 }\r
@@ -910,6 +955,8 @@ NetGetUint32 (
 /**\r
   Put a UINT32 to the byte stream in network byte order.\r
 \r
+  ASSERT if Buf is NULL.\r
+\r
   Converts a UINT32 from host byte order to network byte order. Then copy it to the\r
   byte stream.\r
 \r
@@ -924,6 +971,8 @@ NetPutUint32 (
   IN     UINT32                Data\r
   )\r
 {\r
+  ASSERT (Buf != NULL);\r
+\r
   Data = HTONL (Data);\r
   CopyMem (Buf, &Data, sizeof (UINT32));\r
 }\r
@@ -1022,6 +1071,8 @@ NetListRemoveTail (
 /**\r
   Insert a new node entry after a designated node entry of a doubly linked list.\r
 \r
+  ASSERT if PrevEntry or NewEntry is NULL.\r
+\r
   Inserts a new node entry donated by NewEntry after the node entry donated by PrevEntry\r
   of the doubly linked list.\r
 \r
@@ -1036,6 +1087,8 @@ NetListInsertAfter (
   IN OUT LIST_ENTRY         *NewEntry\r
   )\r
 {\r
+  ASSERT (PrevEntry != NULL && NewEntry != NULL);\r
+\r
   NewEntry->BackLink                = PrevEntry;\r
   NewEntry->ForwardLink             = PrevEntry->ForwardLink;\r
   PrevEntry->ForwardLink->BackLink  = NewEntry;\r
@@ -1046,6 +1099,8 @@ NetListInsertAfter (
 /**\r
   Insert a new node entry before a designated node entry of a doubly linked list.\r
 \r
+  ASSERT if PostEntry or NewEntry is NULL.\r
+\r
   Inserts a new node entry donated by NewEntry after the node entry donated by PostEntry\r
   of the doubly linked list.\r
 \r
@@ -1060,6 +1115,8 @@ NetListInsertBefore (
   IN OUT LIST_ENTRY     *NewEntry\r
   )\r
 {\r
+  ASSERT (PostEntry != NULL && NewEntry != NULL);\r
+\r
   NewEntry->ForwardLink             = PostEntry;\r
   NewEntry->BackLink                = PostEntry->BackLink;\r
   PostEntry->BackLink->ForwardLink  = NewEntry;\r
@@ -1258,7 +1315,6 @@ NetMapClean (
 \r
   If Map is NULL, then ASSERT().\r
 \r
-\r
   @param[in]  Map                   The net map to test.\r
 \r
   @return TRUE if the netmap is empty, otherwise FALSE.\r
@@ -1278,6 +1334,8 @@ NetMapIsEmpty (
 /**\r
   Return the number of the <Key, Value> pairs in the netmap.\r
 \r
+  If Map is NULL, then ASSERT().\r
+\r
   @param[in]  Map                   The netmap to get the entry number.\r
 \r
   @return The entry number in the netmap.\r
@@ -1289,6 +1347,7 @@ NetMapGetCount (
   IN NET_MAP                *Map\r
   )\r
 {\r
+  ASSERT (Map != NULL);\r
   return Map->Count;\r
 }\r
 \r
@@ -1353,6 +1412,7 @@ NetMapAllocItem (
   pairs in the netmap increase by 1.\r
 \r
   If Map is NULL, then ASSERT().\r
+  If Key is NULL, then ASSERT().\r
 \r
   @param[in, out]  Map                   The netmap to insert into.\r
   @param[in]       Key                   The user's key.\r
@@ -1372,7 +1432,7 @@ NetMapInsertHead (
 {\r
   NET_MAP_ITEM              *Item;\r
 \r
-  ASSERT (Map != NULL);\r
+  ASSERT (Map != NULL && Key != NULL);\r
 \r
   Item = NetMapAllocItem (Map);\r
 \r
@@ -1397,6 +1457,7 @@ NetMapInsertHead (
   pairs in the netmap increase by 1.\r
 \r
   If Map is NULL, then ASSERT().\r
+  If Key is NULL, then ASSERT().\r
 \r
   @param[in, out]  Map                   The netmap to insert into.\r
   @param[in]       Key                   The user's key.\r
@@ -1416,7 +1477,7 @@ NetMapInsertTail (
 {\r
   NET_MAP_ITEM              *Item;\r
 \r
-  ASSERT (Map != NULL);\r
+  ASSERT (Map != NULL && Key != NULL);\r
 \r
   Item = NetMapAllocItem (Map);\r
 \r
@@ -1437,6 +1498,9 @@ NetMapInsertTail (
 /**\r
   Check whether the item is in the Map and return TRUE if it is.\r
 \r
+  If Map is NULL, then ASSERT().\r
+  If Item is NULL, then ASSERT().\r
+\r
   @param[in]  Map                   The netmap to search within.\r
   @param[in]  Item                  The item to search.\r
 \r
@@ -1451,6 +1515,8 @@ NetItemInMap (
 {\r
   LIST_ENTRY            *ListEntry;\r
 \r
+  ASSERT (Map != NULL && Item != NULL);\r
+\r
   NET_LIST_FOR_EACH (ListEntry, &Map->Used) {\r
     if (ListEntry == &Item->Link) {\r
       return TRUE;\r
@@ -1468,6 +1534,7 @@ NetItemInMap (
   item with the key to search. It returns the point to the item contains the Key if found.\r
 \r
   If Map is NULL, then ASSERT().\r
+  If Key is NULL, then ASSERT().\r
 \r
   @param[in]  Map                   The netmap to search within.\r
   @param[in]  Key                   The key to search.\r
@@ -1485,7 +1552,7 @@ NetMapFindKey (
   LIST_ENTRY              *Entry;\r
   NET_MAP_ITEM            *Item;\r
 \r
-  ASSERT (Map != NULL);\r
+  ASSERT (Map != NULL && Key != NULL);\r
 \r
   NET_LIST_FOR_EACH (Entry, &Map->Used) {\r
     Item = NET_LIST_USER_STRUCT (Entry, NET_MAP_ITEM, Link);\r
@@ -2088,6 +2155,9 @@ NetLibGetVlanHandle (
 /**\r
   Get MAC address associated with the network service handle.\r
 \r
+  If MacAddress is NULL, then ASSERT().\r
+  If AddressSize is NULL, then ASSERT().\r
+\r
   There should be MNP Service Binding Protocol installed on the input ServiceHandle.\r
   If SNP is installed on the ServiceHandle or its parent handle, MAC address will\r
   be retrieved from SNP. If no SNP found, try to get SNP mode data use MNP.\r
@@ -2192,6 +2262,8 @@ NetLibGetMacAddress (
   Convert MAC address of the NIC associated with specified Service Binding Handle\r
   to a unicode string. Callers are responsible for freeing the string storage.\r
 \r
+  If MacString is NULL, then ASSERT().\r
+\r
   Locate simple network protocol associated with the Service Binding Handle and\r
   get the mac address from SNP. Then convert the mac address into a unicode\r
   string. It takes 2 unicode characters to represent a 1 byte binary buffer.\r
@@ -2291,6 +2363,8 @@ NetLibGetMacString (
 /**\r
   Detect media status for specified network device.\r
 \r
+  If MediaPresent is NULL, then ASSERT().\r
+\r
   The underlying UNDI driver may or may not support reporting media status from\r
   GET_STATUS command (PXE_STATFLAGS_GET_STATUS_NO_MEDIA_SUPPORTED). This routine\r
   will try to invoke Snp->GetStatus() to get the media status: if media already\r
@@ -2399,6 +2473,10 @@ NetLibDetectMedia (
                       Snp->Mode->MCastFilter\r
                       );\r
       ASSERT (MCastFilter != NULL);\r
+      if (MCastFilter == NULL) {\r
+        Status = EFI_OUT_OF_RESOURCES;\r
+        goto Exit;\r
+      }\r
 \r
       ResetMCastFilters = FALSE;\r
     }\r
@@ -2496,6 +2574,185 @@ Exit:
   return Status;\r
 }\r
 \r
+/**\r
+\r
+  Detect media state for a network device. This routine will wait for a period of time at \r
+  a specified checking interval when a certain network is under connecting until connection \r
+  process finishs or timeout. If Aip protocol is supported by low layer drivers, three kinds\r
+  of media states can be detected: EFI_SUCCESS, EFI_NOT_READY and EFI_NO_MEDIA, represents\r
+  connected state, connecting state and no media state respectively. When function detects \r
+  the current state is EFI_NOT_READY, it will loop to wait for next time's check until state \r
+  turns to be EFI_SUCCESS or EFI_NO_MEDIA. If Aip protocol is not supported, function will \r
+  call NetLibDetectMedia() and return state directly.\r
+\r
+  @param[in]   ServiceHandle    The handle where network service binding protocols are\r
+                                installed on.\r
+  @param[in]   Timeout          The maximum number of 100ns units to wait when network\r
+                                is connecting. Zero value means detect once and return\r
+                                immediately.\r
+  @param[out]  MediaState       The pointer to the detected media state.\r
+\r
+  @retval EFI_SUCCESS           Media detection success.\r
+  @retval EFI_INVALID_PARAMETER ServiceHandle is not a valid network device handle or \r
+                                MediaState pointer is NULL.\r
+  @retval EFI_DEVICE_ERROR      A device error occurred.\r
+  @retval EFI_TIMEOUT           Network is connecting but timeout.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+NetLibDetectMediaWaitTimeout (\r
+  IN  EFI_HANDLE            ServiceHandle,\r
+  IN  UINT64                Timeout,\r
+  OUT EFI_STATUS            *MediaState\r
+  )\r
+{\r
+  EFI_STATUS                        Status;\r
+  EFI_HANDLE                        SnpHandle;\r
+  EFI_SIMPLE_NETWORK_PROTOCOL       *Snp;\r
+  EFI_ADAPTER_INFORMATION_PROTOCOL  *Aip;\r
+  EFI_ADAPTER_INFO_MEDIA_STATE      *MediaInfo;\r
+  BOOLEAN                           MediaPresent;\r
+  UINTN                             DataSize;\r
+  EFI_STATUS                        TimerStatus;\r
+  EFI_EVENT                         Timer;\r
+  UINT64                            TimeRemained;\r
+\r
+  if (MediaState == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+  *MediaState = EFI_SUCCESS;\r
+  MediaInfo   = NULL;\r
+\r
+  //\r
+  // Get SNP handle\r
+  //\r
+  Snp = NULL;\r
+  SnpHandle = NetLibGetSnpHandle (ServiceHandle, &Snp);\r
+  if (SnpHandle == NULL) {\r
+    return EFI_INVALID_PARAMETER;\r
+  }\r
+\r
+  Status = gBS->HandleProtocol (\r
+                  SnpHandle,\r
+                  &gEfiAdapterInformationProtocolGuid,\r
+                  (VOID *) &Aip\r
+                  );\r
+  if (EFI_ERROR (Status)) {\r
+\r
+    MediaPresent = TRUE;\r
+    Status = NetLibDetectMedia (ServiceHandle, &MediaPresent);\r
+    if (!EFI_ERROR (Status)) {\r
+      if (MediaPresent) {\r
+        *MediaState = EFI_SUCCESS;\r
+      } else {\r
+        *MediaState = EFI_NO_MEDIA;\r
+      }\r
+    }\r
+\r
+    //\r
+    // NetLibDetectMedia doesn't support EFI_NOT_READY status, return now!\r
+    //\r
+    return Status;\r
+  }\r
+\r
+  Status = Aip->GetInformation (\r
+                  Aip,\r
+                  &gEfiAdapterInfoMediaStateGuid,\r
+                  (VOID **) &MediaInfo,\r
+                  &DataSize\r
+                  );\r
+  if (!EFI_ERROR (Status)) {\r
+\r
+    *MediaState = MediaInfo->MediaState;\r
+    FreePool (MediaInfo);\r
+    if (*MediaState != EFI_NOT_READY || Timeout < MEDIA_STATE_DETECT_TIME_INTERVAL) {\r
+\r
+      return EFI_SUCCESS;\r
+    }\r
+  } else {\r
+\r
+    if (MediaInfo != NULL) {\r
+      FreePool (MediaInfo);\r
+    }\r
+\r
+    if (Status == EFI_UNSUPPORTED) {\r
+\r
+      //\r
+      // If gEfiAdapterInfoMediaStateGuid is not supported, call NetLibDetectMedia to get media state!\r
+      //\r
+      MediaPresent = TRUE;\r
+      Status = NetLibDetectMedia (ServiceHandle, &MediaPresent);\r
+      if (!EFI_ERROR (Status)) {\r
+        if (MediaPresent) {\r
+          *MediaState = EFI_SUCCESS;\r
+        } else {\r
+          *MediaState = EFI_NO_MEDIA;\r
+        }\r
+      }\r
+      return Status;\r
+    }\r
+\r
+    return Status;\r
+  }\r
+\r
+  //\r
+  // Loop to check media state \r
+  //\r
+\r
+  Timer        = NULL;\r
+  TimeRemained = Timeout;\r
+  Status = gBS->CreateEvent (EVT_TIMER, TPL_CALLBACK, NULL, NULL, &Timer);\r
+  if (EFI_ERROR (Status)) {\r
+    return EFI_DEVICE_ERROR;\r
+  }\r
+\r
+  do {\r
+    Status = gBS->SetTimer (\r
+                    Timer,\r
+                    TimerRelative,\r
+                    MEDIA_STATE_DETECT_TIME_INTERVAL\r
+                    );\r
+    if (EFI_ERROR (Status)) {\r
+      gBS->CloseEvent(Timer);\r
+      return EFI_DEVICE_ERROR;\r
+    }\r
+\r
+    do {\r
+      TimerStatus = gBS->CheckEvent (Timer);\r
+      if (!EFI_ERROR (TimerStatus)) {\r
+\r
+        TimeRemained -= MEDIA_STATE_DETECT_TIME_INTERVAL;\r
+        Status = Aip->GetInformation (\r
+                        Aip,\r
+                        &gEfiAdapterInfoMediaStateGuid,\r
+                        (VOID **) &MediaInfo,\r
+                        &DataSize\r
+                        );\r
+        if (!EFI_ERROR (Status)) {\r
+\r
+          *MediaState = MediaInfo->MediaState;\r
+          FreePool (MediaInfo);\r
+        } else {\r
+\r
+          if (MediaInfo != NULL) {\r
+            FreePool (MediaInfo);\r
+          }\r
+          gBS->CloseEvent(Timer);\r
+          return Status;\r
+        }\r
+      }\r
+    } while (TimerStatus == EFI_NOT_READY);\r
+  } while (*MediaState == EFI_NOT_READY && TimeRemained >= MEDIA_STATE_DETECT_TIME_INTERVAL);\r
+\r
+  gBS->CloseEvent(Timer);\r
+  if (*MediaState == EFI_NOT_READY && TimeRemained < MEDIA_STATE_DETECT_TIME_INTERVAL) {\r
+    return EFI_TIMEOUT;\r
+  } else {\r
+    return EFI_SUCCESS;\r
+  }\r
+}\r
+\r
 /**\r
   Check the default address used by the IPv4 driver is static or dynamic (acquired\r
   from DHCP).\r
@@ -2551,6 +2808,8 @@ ON_EXIT:
 /**\r
   Create an IPv4 device path node.\r
 \r
+  If Node is NULL, then ASSERT().\r
+\r
   The header type of IPv4 device path node is MESSAGING_DEVICE_PATH.\r
   The header subtype of IPv4 device path node is MSG_IPv4_DP.\r
   Get other info from parameters to make up the whole IPv4 device path node.\r
@@ -2578,6 +2837,8 @@ NetLibCreateIPv4DPathNode (
   IN BOOLEAN               UseDefaultAddress\r
   )\r
 {\r
+  ASSERT (Node != NULL);\r
+\r
   Node->Header.Type    = MESSAGING_DEVICE_PATH;\r
   Node->Header.SubType = MSG_IPv4_DP;\r
   SetDevicePathNodeLength (&Node->Header, sizeof (IPv4_DEVICE_PATH));\r
@@ -2608,6 +2869,10 @@ NetLibCreateIPv4DPathNode (
 /**\r
   Create an IPv6 device path node.\r
 \r
+  If Node is NULL, then ASSERT().\r
+  If LocalIp is NULL, then ASSERT().\r
+  If RemoteIp is NULL, then ASSERT().\r
+\r
   The header type of IPv6 device path node is MESSAGING_DEVICE_PATH.\r
   The header subtype of IPv6 device path node is MSG_IPv6_DP.\r
   Get other info from parameters to make up the whole IPv6 device path node.\r
@@ -2633,6 +2898,8 @@ NetLibCreateIPv6DPathNode (
   IN UINT16                Protocol\r
   )\r
 {\r
+  ASSERT (Node != NULL && LocalIp != NULL && RemoteIp != NULL);\r
+\r
   Node->Header.Type    = MESSAGING_DEVICE_PATH;\r
   Node->Header.SubType = MSG_IPv6_DP;\r
   SetDevicePathNodeLength (&Node->Header, sizeof (IPv6_DEVICE_PATH));\r
@@ -2657,6 +2924,8 @@ NetLibCreateIPv6DPathNode (
 /**\r
   Find the UNDI/SNP handle from controller and protocol GUID.\r
 \r
+  If ProtocolGuid is NULL, then ASSERT().\r
+\r
   For example, IP will open a MNP child to transmit/receive\r
   packets, when MNP is stopped, IP should also be stopped. IP\r
   needs to find its own private data which is related the IP's\r
@@ -2684,6 +2953,8 @@ NetLibGetNicHandle (
   UINTN                               OpenCount;\r
   UINTN                               Index;\r
 \r
+  ASSERT (ProtocolGuid != NULL);\r
+\r
   Status = gBS->OpenProtocolInformation (\r
                   Controller,\r
                   ProtocolGuid,\r
@@ -2965,6 +3236,8 @@ NetLibIp6ToStr (
 /**\r
   This function obtains the system guid from the smbios table.\r
 \r
+  If SystemGuid is NULL, then ASSERT().\r
+\r
   @param[out]  SystemGuid     The pointer of the returned system guid.\r
 \r
   @retval EFI_SUCCESS         Successfully obtained the system guid.\r
@@ -2984,6 +3257,8 @@ NetLibGetSystemGuid (
   SMBIOS_STRUCTURE_POINTER      SmbiosEnd;\r
   CHAR8                         *String;\r
 \r
+  ASSERT (SystemGuid != NULL);\r
+\r
   SmbiosTable = NULL;\r
   Status = EfiGetSystemConfigurationTable (&gEfiSmbios3TableGuid, (VOID **) &Smbios30Table);\r
   if (!(EFI_ERROR (Status) || Smbios30Table == NULL)) {\r
@@ -3050,7 +3325,10 @@ NetLibGetSystemGuid (
 }\r
 \r
 /**\r
-  Create Dns QName according the queried domain name. \r
+  Create Dns QName according the queried domain name.\r
+\r
+  If DomainName is NULL, then ASSERT().\r
+  \r
   QName is a domain name represented as a sequence of labels, \r
   where each label consists of a length octet followed by that \r
   number of octets. The QName terminates with the zero \r
@@ -3076,6 +3354,8 @@ NetLibCreateDnsQName (
   UINTN                 Len;\r
   UINTN                 Index;\r
 \r
+  ASSERT (DomainName != NULL);\r
+\r
   QueryName     = NULL;\r
   QueryNameSize = 0;\r
   Header        = NULL;\r