Be more careful with fread in various places.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include "util.h"
26 #include "exceptions.h"
27 #include "dcp_content_type.h"
28 #include "filter.h"
29 #include "cinema_sound_processor.h"
30 #include "config.h"
31 #include "ratio.h"
32 #include "job.h"
33 #include "cross.h"
34 #include "video_content.h"
35 #include "rect.h"
36 #include "digester.h"
37 #include "audio_processor.h"
38 #include "compose.hpp"
39 #include "audio_buffers.h"
40 #include <dcp/locale_convert.h>
41 #include <dcp/util.h>
42 #include <dcp/raw_convert.h>
43 #include <dcp/picture_asset.h>
44 #include <dcp/sound_asset.h>
45 #include <dcp/subtitle_asset.h>
46 extern "C" {
47 #include <libavfilter/avfilter.h>
48 #include <libavformat/avformat.h>
49 #include <libavcodec/avcodec.h>
50 }
51 #include <curl/curl.h>
52 #include <glib.h>
53 #include <pangomm/init.h>
54 #include <boost/algorithm/string.hpp>
55 #include <boost/range/algorithm/replace_if.hpp>
56 #include <boost/thread.hpp>
57 #include <boost/filesystem.hpp>
58 #ifdef DCPOMATIC_WINDOWS
59 #include <boost/locale.hpp>
60 #include <dbghelp.h>
61 #endif
62 #include <signal.h>
63 #include <iomanip>
64 #include <iostream>
65 #include <fstream>
66 #include <climits>
67 #include <stdexcept>
68 #ifdef DCPOMATIC_POSIX
69 #include <execinfo.h>
70 #include <cxxabi.h>
71 #endif
72
73 #include "i18n.h"
74
75 using std::string;
76 using std::setfill;
77 using std::ostream;
78 using std::endl;
79 using std::vector;
80 using std::min;
81 using std::max;
82 using std::map;
83 using std::list;
84 using std::multimap;
85 using std::istream;
86 using std::pair;
87 using std::cout;
88 using std::bad_alloc;
89 using std::set_terminate;
90 using std::make_pair;
91 using boost::shared_ptr;
92 using boost::thread;
93 using boost::optional;
94 using boost::lexical_cast;
95 using boost::bad_lexical_cast;
96 using dcp::Size;
97 using dcp::raw_convert;
98 using dcp::locale_convert;
99
100 /** Path to our executable, required by the stacktrace stuff and filled
101  *  in during App::onInit().
102  */
103 string program_name;
104 bool is_batch_converter = false;
105 static boost::thread::id ui_thread;
106 static boost::filesystem::path backtrace_file;
107
108 /** Convert some number of seconds to a string representation
109  *  in hours, minutes and seconds.
110  *
111  *  @param s Seconds.
112  *  @return String of the form H:M:S (where H is hours, M
113  *  is minutes and S is seconds).
114  */
115 string
116 seconds_to_hms (int s)
117 {
118         int m = s / 60;
119         s -= (m * 60);
120         int h = m / 60;
121         m -= (h * 60);
122
123         char buffer[64];
124         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
125         return buffer;
126 }
127
128 string
129 time_to_hmsf (DCPTime time, Frame rate)
130 {
131         Frame f = time.frames_round (rate);
132         int s = f / rate;
133         f -= (s * rate);
134         int m = s / 60;
135         s -= m * 60;
136         int h = m / 60;
137         m -= h * 60;
138
139         char buffer[64];
140         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
141         return buffer;
142 }
143
144 /** @param s Number of seconds.
145  *  @return String containing an approximate description of s (e.g. "about 2 hours")
146  */
147 string
148 seconds_to_approximate_hms (int s)
149 {
150         int m = s / 60;
151         s -= (m * 60);
152         int h = m / 60;
153         m -= (h * 60);
154
155         string ap;
156
157         bool hours = h > 0;
158         bool minutes = h < 6 && m > 0;
159         bool seconds = h == 0 && m < 10 && s > 0;
160
161         if (m > 30 && !minutes) {
162                 /* round up the hours */
163                 ++h;
164         }
165         if (s > 30 && !seconds) {
166                 /* round up the minutes */
167                 ++m;
168                 if (m == 60) {
169                         m = 0;
170                         minutes = false;
171                         ++h;
172                 }
173         }
174
175         if (hours) {
176                 /// TRANSLATORS: h here is an abbreviation for hours
177                 ap += locale_convert<string>(h) + _("h");
178
179                 if (minutes || seconds) {
180                         ap += N_(" ");
181                 }
182         }
183
184         if (minutes) {
185                 /// TRANSLATORS: m here is an abbreviation for minutes
186                 ap += locale_convert<string>(m) + _("m");
187
188                 if (seconds) {
189                         ap += N_(" ");
190                 }
191         }
192
193         if (seconds) {
194                 /* Seconds */
195                 /// TRANSLATORS: s here is an abbreviation for seconds
196                 ap += locale_convert<string>(s) + _("s");
197         }
198
199         return ap;
200 }
201
202 double
203 seconds (struct timeval t)
204 {
205         return t.tv_sec + (double (t.tv_usec) / 1e6);
206 }
207
208 #ifdef DCPOMATIC_WINDOWS
209
210 /** Resolve symbol name and source location given the path to the executable */
211 int
212 addr2line (void const * const addr)
213 {
214         char addr2line_cmd[512] = { 0 };
215         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
216         return system(addr2line_cmd);
217 }
218
219 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
220  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
221  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
222  */
223 LONG WINAPI
224 exception_handler(struct _EXCEPTION_POINTERS * info)
225 {
226         FILE* f = fopen_boost (backtrace_file, "w");
227         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
228         fclose(f);
229
230         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
231                 CONTEXT* context = info->ContextRecord;
232                 SymInitialize (GetCurrentProcess (), 0, true);
233
234                 STACKFRAME frame = { 0 };
235
236                 /* setup initial stack frame */
237 #if _WIN64
238                 frame.AddrPC.Offset    = context->Rip;
239                 frame.AddrStack.Offset = context->Rsp;
240                 frame.AddrFrame.Offset = context->Rbp;
241 #else
242                 frame.AddrPC.Offset    = context->Eip;
243                 frame.AddrStack.Offset = context->Esp;
244                 frame.AddrFrame.Offset = context->Ebp;
245 #endif
246                 frame.AddrPC.Mode      = AddrModeFlat;
247                 frame.AddrStack.Mode   = AddrModeFlat;
248                 frame.AddrFrame.Mode   = AddrModeFlat;
249
250                 while (
251                         StackWalk (
252                                 IMAGE_FILE_MACHINE_I386,
253                                 GetCurrentProcess (),
254                                 GetCurrentThread (),
255                                 &frame,
256                                 context,
257                                 0,
258                                 SymFunctionTableAccess,
259                                 SymGetModuleBase,
260                                 0
261                                 )
262                         ) {
263                         addr2line((void *) frame.AddrPC.Offset);
264                 }
265         } else {
266 #ifdef _WIN64
267                 addr2line ((void *) info->ContextRecord->Rip);
268 #else
269                 addr2line ((void *) info->ContextRecord->Eip);
270 #endif
271         }
272
273         return EXCEPTION_CONTINUE_SEARCH;
274 }
275 #endif
276
277 void
278 set_backtrace_file (boost::filesystem::path p)
279 {
280         backtrace_file = p;
281 }
282
283 /** This is called when there is an unhandled exception.  Any
284  *  backtrace in this function is useless on Windows as the stack has
285  *  already been unwound from the throw; we have the gdb wrap hack to
286  *  cope with that.
287  */
288 void
289 terminate ()
290 {
291         try {
292                 static bool tried_throw = false;
293                 // try once to re-throw currently active exception
294                 if (!tried_throw) {
295                         tried_throw = true;
296                         throw;
297                 }
298         }
299         catch (const std::exception &e) {
300                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
301                           << e.what() << std::endl;
302         }
303         catch (...) {
304                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
305                           << std::endl;
306         }
307
308         abort();
309 }
310
311 void
312 dcpomatic_setup_path_encoding ()
313 {
314 #ifdef DCPOMATIC_WINDOWS
315         /* Dark voodoo which, I think, gets boost::filesystem::path to
316            correctly convert UTF-8 strings to paths, and also paths
317            back to UTF-8 strings (on path::string()).
318
319            After this, constructing boost::filesystem::paths from strings
320            converts from UTF-8 to UTF-16 inside the path.  Then
321            path::string().c_str() gives UTF-8 and
322            path::c_str()          gives UTF-16.
323
324            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
325            so things are much simpler.
326         */
327         std::locale::global (boost::locale::generator().generate (""));
328         boost::filesystem::path::imbue (std::locale ());
329 #endif
330 }
331
332 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
333  *  Must be called from the UI thread, if there is one.
334  */
335 void
336 dcpomatic_setup ()
337 {
338 #ifdef DCPOMATIC_WINDOWS
339         boost::filesystem::path p = g_get_user_config_dir ();
340         p /= "backtrace.txt";
341         set_backtrace_file (p);
342         SetUnhandledExceptionFilter(exception_handler);
343 #endif
344
345         av_register_all ();
346         avfilter_register_all ();
347
348 #ifdef DCPOMATIC_OSX
349         /* Add our library directory to the libltdl search path so that
350            xmlsec can find xmlsec1-openssl.
351         */
352         boost::filesystem::path lib = app_contents ();
353         lib /= "Frameworks";
354         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
355 #endif
356
357         set_terminate (terminate);
358
359         Pango::init ();
360         dcp::init ();
361
362         Ratio::setup_ratios ();
363         PresetColourConversion::setup_colour_conversion_presets ();
364         VideoContentScale::setup_scales ();
365         DCPContentType::setup_dcp_content_types ();
366         Filter::setup_filters ();
367         CinemaSoundProcessor::setup_cinema_sound_processors ();
368         AudioProcessor::setup_audio_processors ();
369
370         curl_global_init (CURL_GLOBAL_ALL);
371
372         ui_thread = boost::this_thread::get_id ();
373 }
374
375 #ifdef DCPOMATIC_WINDOWS
376 boost::filesystem::path
377 mo_path ()
378 {
379         wchar_t buffer[512];
380         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
381         boost::filesystem::path p (buffer);
382         p = p.parent_path ();
383         p = p.parent_path ();
384         p /= "locale";
385         return p;
386 }
387 #endif
388
389 #ifdef DCPOMATIC_OSX
390 boost::filesystem::path
391 mo_path ()
392 {
393         return "DCP-o-matic 2.app/Contents/Resources";
394 }
395 #endif
396
397 void
398 dcpomatic_setup_gettext_i18n (string lang)
399 {
400 #ifdef DCPOMATIC_LINUX
401         lang += ".UTF8";
402 #endif
403
404         if (!lang.empty ()) {
405                 /* Override our environment language.  Note that the caller must not
406                    free the string passed into putenv().
407                 */
408                 string s = String::compose ("LANGUAGE=%1", lang);
409                 putenv (strdup (s.c_str ()));
410                 s = String::compose ("LANG=%1", lang);
411                 putenv (strdup (s.c_str ()));
412                 s = String::compose ("LC_ALL=%1", lang);
413                 putenv (strdup (s.c_str ()));
414         }
415
416         setlocale (LC_ALL, "");
417         textdomain ("libdcpomatic2");
418
419 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
420         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
421         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
422 #endif
423
424 #ifdef DCPOMATIC_LINUX
425         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
426 #endif
427 }
428
429 /** Compute a digest of the first and last `size' bytes of a set of files. */
430 string
431 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
432 {
433         boost::scoped_array<char> buffer (new char[size]);
434         Digester digester;
435
436         /* Head */
437         boost::uintmax_t to_do = size;
438         char* p = buffer.get ();
439         int i = 0;
440         while (i < int64_t (files.size()) && to_do > 0) {
441                 FILE* f = fopen_boost (files[i], "rb");
442                 if (!f) {
443                         throw OpenFileError (files[i].string(), errno, true);
444                 }
445
446                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
447                 checked_fread (p, this_time, f, files[i]);
448                 p += this_time;
449                 to_do -= this_time;
450                 fclose (f);
451
452                 ++i;
453         }
454         digester.add (buffer.get(), size - to_do);
455
456         /* Tail */
457         to_do = size;
458         p = buffer.get ();
459         i = files.size() - 1;
460         while (i >= 0 && to_do > 0) {
461                 FILE* f = fopen_boost (files[i], "rb");
462                 if (!f) {
463                         throw OpenFileError (files[i].string(), errno, true);
464                 }
465
466                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
467                 dcpomatic_fseek (f, -this_time, SEEK_END);
468                 checked_fread (p, this_time, f, files[i]);
469                 p += this_time;
470                 to_do -= this_time;
471                 fclose (f);
472
473                 --i;
474         }
475         digester.add (buffer.get(), size - to_do);
476
477         return digester.get ();
478 }
479
480 /** Round a number up to the nearest multiple of another number.
481  *  @param c Index.
482  *  @param stride Array of numbers to round, indexed by c.
483  *  @param t Multiple to round to.
484  *  @return Rounded number.
485  */
486 int
487 stride_round_up (int c, int const * stride, int t)
488 {
489         int const a = stride[c] + (t - 1);
490         return a - (a % t);
491 }
492
493 /** Trip an assert if the caller is not in the UI thread */
494 void
495 ensure_ui_thread ()
496 {
497         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
498 }
499
500 string
501 audio_channel_name (int c)
502 {
503         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
504
505         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
506         /// enhancement channel (sub-woofer).
507         string const channels[] = {
508                 _("Left"),
509                 _("Right"),
510                 _("Centre"),
511                 _("Lfe (sub)"),
512                 _("Left surround"),
513                 _("Right surround"),
514                 _("Hearing impaired"),
515                 _("Visually impaired"),
516                 _("Left centre"),
517                 _("Right centre"),
518                 _("Left rear surround"),
519                 _("Right rear surround"),
520                 _("D-BOX primary"),
521                 _("D-BOX secondary"),
522                 _("Unused"),
523                 _("Unused")
524         };
525
526         return channels[c];
527 }
528
529 string
530 short_audio_channel_name (int c)
531 {
532         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
533
534         /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
535         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
536         /// VI is the visually-impaired audio track (audio describe).  DBP is the D-BOX
537         /// primary channel and DBS is the D-BOX secondary channel.
538         string const channels[] = {
539                 _("L"),
540                 _("R"),
541                 _("C"),
542                 _("Lfe"),
543                 _("Ls"),
544                 _("Rs"),
545                 _("HI"),
546                 _("VI"),
547                 _("Lc"),
548                 _("Rc"),
549                 _("BsL"),
550                 _("BsR"),
551                 _("DBP"),
552                 _("DBS"),
553                 "",
554                 ""
555         };
556
557         return channels[c];
558 }
559
560
561 bool
562 valid_image_file (boost::filesystem::path f)
563 {
564         if (boost::starts_with (f.leaf().string(), "._")) {
565                 return false;
566         }
567
568         string ext = f.extension().string();
569         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
570         return (
571                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
572                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
573                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
574                 ext == ".jpf"
575                 );
576 }
577
578 bool
579 valid_sound_file (boost::filesystem::path f)
580 {
581         if (boost::starts_with (f.leaf().string(), "._")) {
582                 return false;
583         }
584
585         string ext = f.extension().string();
586         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
587         return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
588 }
589
590 bool
591 valid_j2k_file (boost::filesystem::path f)
592 {
593         string ext = f.extension().string();
594         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
595         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
596 }
597
598 string
599 tidy_for_filename (string f)
600 {
601         boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
602         return f;
603 }
604
605 dcp::Size
606 fit_ratio_within (float ratio, dcp::Size full_frame)
607 {
608         if (ratio < full_frame.ratio ()) {
609                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
610         }
611
612         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
613 }
614
615 void *
616 wrapped_av_malloc (size_t s)
617 {
618         void* p = av_malloc (s);
619         if (!p) {
620                 throw bad_alloc ();
621         }
622         return p;
623 }
624
625 map<string, string>
626 split_get_request (string url)
627 {
628         enum {
629                 AWAITING_QUESTION_MARK,
630                 KEY,
631                 VALUE
632         } state = AWAITING_QUESTION_MARK;
633
634         map<string, string> r;
635         string k;
636         string v;
637         for (size_t i = 0; i < url.length(); ++i) {
638                 switch (state) {
639                 case AWAITING_QUESTION_MARK:
640                         if (url[i] == '?') {
641                                 state = KEY;
642                         }
643                         break;
644                 case KEY:
645                         if (url[i] == '=') {
646                                 v.clear ();
647                                 state = VALUE;
648                         } else {
649                                 k += url[i];
650                         }
651                         break;
652                 case VALUE:
653                         if (url[i] == '&') {
654                                 r.insert (make_pair (k, v));
655                                 k.clear ();
656                                 state = KEY;
657                         } else {
658                                 v += url[i];
659                         }
660                         break;
661                 }
662         }
663
664         if (state == VALUE) {
665                 r.insert (make_pair (k, v));
666         }
667
668         return r;
669 }
670
671 string
672 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
673 {
674         dcp::NameFormat::Map values;
675         values['t'] = "j2c";
676         values['r'] = raw_convert<string> (reel_index + 1);
677         values['n'] = raw_convert<string> (reel_count);
678         if (summary) {
679                 values['c'] = careful_string_filter (summary.get());
680         }
681         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
682 }
683
684 string
685 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
686 {
687         dcp::NameFormat::Map values;
688         values['t'] = "pcm";
689         values['r'] = raw_convert<string> (reel_index + 1);
690         values['n'] = raw_convert<string> (reel_count);
691         if (summary) {
692                 values['c'] = careful_string_filter (summary.get());
693         }
694         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
695 }
696
697 float
698 relaxed_string_to_float (string s)
699 {
700         try {
701                 boost::algorithm::replace_all (s, ",", ".");
702                 return lexical_cast<float> (s);
703         } catch (bad_lexical_cast) {
704                 boost::algorithm::replace_all (s, ".", ",");
705                 return lexical_cast<float> (s);
706         }
707 }
708
709 string
710 careful_string_filter (string s)
711 {
712         /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
713            There's no apparent list of what really is allowed, so this is a guess.
714            Safety first and all that.
715         */
716
717         string out;
718         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
719         for (size_t i = 0; i < s.size(); ++i) {
720                 if (allowed.find (s[i]) != string::npos) {
721                         out += s[i];
722                 }
723         }
724
725         return out;
726 }
727
728 /** @param mapped List of mapped audio channels from a Film.
729  *  @param channels Total number of channels in the Film.
730  *  @return First: number of non-LFE channels, second: number of LFE channels.
731  */
732 pair<int, int>
733 audio_channel_types (list<int> mapped, int channels)
734 {
735         int non_lfe = 0;
736         int lfe = 0;
737
738         BOOST_FOREACH (int i, mapped) {
739                 if (i >= channels) {
740                         /* This channel is mapped but is not included in the DCP */
741                         continue;
742                 }
743
744                 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
745                         ++lfe;
746                 } else {
747                         ++non_lfe;
748                 }
749         }
750
751         return make_pair (non_lfe, lfe);
752 }
753
754 shared_ptr<AudioBuffers>
755 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
756 {
757         shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
758         mapped->make_silent ();
759
760         for (int i = 0; i < map.input_channels(); ++i) {
761                 for (int j = 0; j < mapped->channels(); ++j) {
762                         if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
763                                 mapped->accumulate_channel (
764                                         input.get(),
765                                         i,
766                                         static_cast<dcp::Channel> (j),
767                                         map.get (i, static_cast<dcp::Channel> (j))
768                                         );
769                         }
770                 }
771         }
772
773         return mapped;
774 }
775
776 Eyes
777 increment_eyes (Eyes e)
778 {
779         if (e == EYES_LEFT) {
780                 return EYES_RIGHT;
781         }
782
783         return EYES_LEFT;
784 }
785
786 void
787 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
788 {
789         size_t N = fread (ptr, 1, size, stream);
790         if (N != size) {
791                 if (ferror(stream)) {
792                         throw FileError (String::compose("fread error %1", errno), path);
793                 } else {
794                         throw FileError ("Unexpected short read", path);
795                 }
796         }
797 }