Skip to content

Commit

Permalink
main.cpp: Defeat impact of possible buffer overflow
Browse files Browse the repository at this point in the history
'valgrind --tool=exp-sgcheck' detected an invalid write
at former line 491 (sprintf...).

Using snprintf avoids this condition, and allows data loss
detection (Q: why not use the safer c++ strings, A:???).

This fix has some observable impact on bsmap's output,
although I've only seen a change in the amount of whitespace.

I also assume that this might be the cause for the crashes
at the end of bsmap execution.
  • Loading branch information
thomas committed Oct 9, 2017
1 parent 2edd932 commit 1dcfe72
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
#include <pthread.h>
#endif

#define LINEBUFFSIZE 1024

using namespace std;

//global variables
Expand Down Expand Up @@ -397,7 +399,8 @@ int check_ifile_format(string &filename, int gz_flag) {
}

void RunProcess(void) {
char _ch[256]; string _str="@HD\tVN:1.0\n";
char _ch[LINEBUFFSIZE];
string _str="@HD\tVN:1.0\n";
if(out_align_file.size()>4){
if(out_align_file.compare(out_align_file.size()-4,4,".sam")==0) param.out_sam=1;
else if (out_align_file.compare(out_align_file.size()-4,4,".bam")==0) param.out_sam=2;
Expand Down Expand Up @@ -483,11 +486,19 @@ void RunProcess(void) {
}

if(param.out_sam&&param.sam_header) {
int ret_len;
for(bit32_t i=0;i<ref.total_num;i++){
sprintf(_ch,"@SQ\tSN:%s\tLN:%u\n",ref.title[i<<1].name.c_str(),ref.title[i<<1].size);
ret_len=snprintf(_ch,LINEBUFFSIZE,"@SQ\tSN:%s\tLN:%u\n",ref.title[i<<1].name.c_str(),ref.title[i<<1].size);
if (ret_len>=LINEBUFFSIZE) {
cerr<<"Buffer error, output was truncated (increase LINEBUFFSIZE in main.cpp and recompile)."<<endl;
}
_str.append(_ch);
}
sprintf(_ch,"@PG\tID:BSMAP\tVN:%s\tCL:\"%s\"\n",version,command_line.c_str()); _str.append(_ch);
ret_len=snprintf(_ch,LINEBUFFSIZE,"@PG\tID:BSMAP\tVN:%s\tCL:\"%s\"\n",version,command_line.c_str());
if (ret_len>=LINEBUFFSIZE) {
cerr<<"Buffer error, output was truncated (increase LINEBUFFSIZE in main.cpp and recompile)."<<endl;
}
_str.append(_ch);
if(param.stdout) cout<<_str;
else if(param.pipe_out) fwrite(_str.c_str(),1,_str.size(),pout);
else fout<<_str;
Expand Down

0 comments on commit 1dcfe72

Please sign in to comment.