Now PVS-Studio knows even better what kind of animal this is - strlen

0824_DataFlow_And_Strlen_ru / image1.png







Somehow it happened so unfairly that we almost do not pay attention in our notes to the improvement of the internal mechanisms of the analyzer, in contrast to new diagnostics. So let's take a look at a useful new enhancement for data flow analysis for a change.







It all started with a tweet from JetBrains CLion IDE



Twitter JetBrains , CLion.







0824_DataFlow_And_Strlen_ru / image2.png







PVS-Studio CLion, , . PVS-Studio CLion, .







0824_DataFlow_And_Strlen_ru / image3.png







:









. ! . ? - , . .







Data Flow



, , , , PVS-Studio . , . :







bool foo()
{
  unsigned N = 2;
  for (unsigned i = 0; i < N; ++i)
  {
    bool stop = (i - 1 == N);
    if (stop)
      return true;
  }
  return false;
}
      
      





, stop false.







false? :







  • i = [0; 1];
  • i-1 = [0; 0] U [UINT_MAX; UINT_MAX];
  • N, , { 0, UINT_MAX };
  • .


. , (wrap) .







PVS-Studio . , .







, , . , , strlen. , .







, , FCEUX. Assemble.







int Assemble(unsigned char *output, int addr, char *str) {
  output[0] = output[1] = output[2] = 0;
  char astr[128],ins[4];
  if ((!strlen(str)) || (strlen(str) > 0x127)) return 1;
  strcpy(astr,str);
  ....
}
      
      





? , , - . , , , .







PVS-Studio: V512 A call of the 'strcpy' function will lead to overflow of the buffer 'astr'. asm.cpp 21







? . :







int Assemble(char *str) {
  char astr[128];
  if ((!strlen(str)) || (strlen(str) > 0x127)) return 1;
  strcpy(astr,str);
  ....
}
      
      





128 , , . , 127 ( ).







? , . ?! 0x127?!







127. 127 :)







. , 295.







, :







int Assemble(char *str) {
  char astr[128];
  if ((!strlen(str)) || (strlen(str) > 295)) return 1;
  strcpy(astr,str);
  ....
}
      
      





, , .







, , strlen . strlen. , , :).







PVS-Studio , str [1..295], , , astr.







0824_DataFlow_And_Strlen_ru / image4.png









FCEUX. , . . , , :







int Assemble(unsigned char *output, int addr, char *str) {
  output[0] = output[1] = output[2] = 0;
  char astr[128],ins[4];
  int len = strlen(str);
  if ((!len) || (len > 0x127)) return 1;
  strcpy(astr,str);
  ....
}
      
      





, , , . , len str. , len.







PVS-Studio . , ! .







, , ? . , . , - - . , .







, C++14, C++17 .., . , header-only C++ (awesome-hpp).









. , :







  1. ,
  2. PVS-Studio:
  3. , PVS-Studio


PVS-Studio .







, : Andrey Karpov. PVS-Studio Learns What strlen is All About.








All Articles