Commit e32fd66bb95adfa0e8cb0e060aa84465ebe2c5a5

Authored by Josh Klontz
1 parent b68b869c

made br_iterate_utemplates_file more robust

Showing 1 changed file with 35 additions and 9 deletions
openbr/universal_template.cpp
@@ -58,18 +58,44 @@ static void callAndFree(br_utemplate_callback callback, br_utemplate t, br_callb @@ -58,18 +58,44 @@ static void callAndFree(br_utemplate_callback callback, br_utemplate t, br_callb
58 void br_iterate_utemplates_file(FILE *file, br_utemplate_callback callback, br_callback_context context, bool parallel) 58 void br_iterate_utemplates_file(FILE *file, br_utemplate_callback callback, br_callback_context context, bool parallel)
59 { 59 {
60 QFutureSynchronizer<void> futures; 60 QFutureSynchronizer<void> futures;
61 - while (!feof(file)) { 61 + while (true) {
62 br_utemplate t = (br_utemplate) malloc(sizeof(br_universal_template)); 62 br_utemplate t = (br_utemplate) malloc(sizeof(br_universal_template));
63 63
64 - if (fread(t, sizeof(br_universal_template), 1, file) > 0) {  
65 - t = (br_utemplate) realloc(t, sizeof(br_universal_template) + t->size);  
66 - if (fread(t+1, 1, t->size, file) != t->size)  
67 - qFatal("Unexepected EOF when reading universal template data.");  
68 - if (parallel) futures.addFuture(QtConcurrent::run(callAndFree, callback, t, context));  
69 - else callAndFree(callback, t, context);  
70 - } else {  
71 - free(t); 64 + int bytesRemaining = sizeof(br_universal_template);
  65 + while (bytesRemaining > 0) {
  66 + bytesRemaining -= fread(reinterpret_cast<char*>(t) + sizeof(br_universal_template) - bytesRemaining, 1, bytesRemaining, file);
  67 +
  68 + if (feof(file)) {
  69 + if (bytesRemaining == sizeof(br_universal_template)) {
  70 + free(t);
  71 + return;
  72 + } else {
  73 + qFatal("Unexpected end of file when reading template metadata.");
  74 + }
  75 + }
  76 +
  77 + if (ferror(file)) {
  78 + perror(NULL);
  79 + qFatal("Error while reading template metadata.");
  80 + }
72 } 81 }
  82 +
  83 + t = (br_utemplate) realloc(t, sizeof(br_universal_template) + t->size);
  84 + bytesRemaining = t->size;
  85 + while (bytesRemaining > 0) {
  86 + bytesRemaining -= fread(&t->data[t->size - bytesRemaining], 1, bytesRemaining, file);
  87 +
  88 + if (feof(file))
  89 + qFatal("Unexpected end of file when reading template data.");
  90 +
  91 + if (ferror(file)) {
  92 + perror(NULL);
  93 + qFatal("Error while reading template data.");
  94 + }
  95 + }
  96 +
  97 + if (parallel) futures.addFuture(QtConcurrent::run(callAndFree, callback, t, context));
  98 + else callAndFree(callback, t, context);
73 } 99 }
74 futures.waitForFinished(); 100 futures.waitForFinished();
75 } 101 }