text: /* TEMPLATE GENERATED TESTCASE FILE
  Filename: CWE194_Unexpected_Sign_Extension__listen_socket_malloc_54e.c
  Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
  Template File: sources-sink-54e.tmpl.c
  */
  /*
   * @description
   * CWE: 194 Unexpected Sign Extension
   * BadSource: listen_socket Read data using a listen socket (server side)
   * GoodSource: Positive integer
   * Sink: malloc
   *    BadSink : Allocate memory using malloc() with the size of data
   * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
   *
   * */
  
  #include "std_testcase.h"
  
  #ifdef _WIN32
  #include <winsock2.h>
  #include <windows.h>
  #include <direct.h>
  #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
  #define CLOSE_SOCKET closesocket
  #else
  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <unistd.h>
  #define INVALID_SOCKET -1
  #define SOCKET_ERROR -1
  #define CLOSE_SOCKET close
  #define SOCKET int
  #endif
  
  #define TCP_PORT 27015
  #define LISTEN_BACKLOG 5
  /* Must be at least 8 for atoi() to work properly */
  #define CHAR_ARRAY_SIZE 8
  
  /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
  
  #ifndef OMITBAD
  
  void CWE194_Unexpected_Sign_Extension__listen_socket_malloc_54e_badSink(short data)
  {
      /* Assume we want to allocate a relatively small buffer */
      if (data < 100)
      {
          /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
           * the conversion will cause malloc() to allocate a very large amount of data or fail */
          char * dataBuffer = (char *)malloc(data);
          if (dataBuffer == NULL) {exit(-1);}
          /* Do something with dataBuffer */
          memset(dataBuffer, 'A', data-1);
          dataBuffer[data-1] = '\0';
          printLine(dataBuffer);
          free(dataBuffer);
      }
  }
  
  #endif /* OMITBAD */
  
  #ifndef OMITGOOD
  
  /* goodG2B uses the GoodSource with the BadSink */
  void CWE194_Unexpected_Sign_Extension__listen_socket_malloc_54e_goodG2BSink(short data)
  {
      /* Assume we want to allocate a relatively small buffer */
      if (data < 100)
      {
          /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative,
           * the conversion will cause malloc() to allocate a very large amount of data or fail */
          char * dataBuffer = (char *)malloc(data);
          if (dataBuffer == NULL) {exit(-1);}
          /* Do something with dataBuffer */
          memset(dataBuffer, 'A', data-1);
          dataBuffer[data-1] = '\0';
          printLine(dataBuffer);
          free(dataBuffer);
      }
  }
  
  #endif /* OMITGOOD */
  