Agora o PVS-Studio sabe ainda melhor que tipo de animal é este - strlen

0824_DataFlow_And_Strlen_ru / image1.png







De alguma forma, aconteceu de forma tão injusta que quase não prestamos atenção em nossas notas ao aprimoramento dos mecanismos internos do analisador, em contraste com novos diagnósticos. Então, vamos dar uma olhada em um novo aprimoramento útil para análise de fluxo de dados para uma mudança.







Tudo começou com um tweet do IDE JetBrains CLion



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