getline.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* main.c - the normal mode main routine */
  2. /*
  3. * GRUB -- GRand Unified Bootloader
  4. * Copyright (C) 2000,2001,2002,2003,2005,2006,2007,2008,2009,2013 Free Software Foundation, Inc.
  5. *
  6. * GRUB 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 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <grub/kernel.h>
  20. #include <grub/normal.h>
  21. #include <grub/dl.h>
  22. #include <grub/misc.h>
  23. #include <grub/file.h>
  24. #include <grub/mm.h>
  25. #include <grub/term.h>
  26. #include <grub/env.h>
  27. #include <grub/parser.h>
  28. #include <grub/reader.h>
  29. #include <grub/menu_viewer.h>
  30. #include <grub/auth.h>
  31. #include <grub/i18n.h>
  32. #include <grub/charset.h>
  33. #include <grub/script_sh.h>
  34. /* Read a line from the file FILE. */
  35. char *
  36. grub_file_getline (grub_file_t file)
  37. {
  38. char c;
  39. grub_size_t pos = 0;
  40. char *cmdline;
  41. int have_newline = 0;
  42. grub_size_t max_len = 64;
  43. /* Initially locate some space. */
  44. cmdline = grub_malloc (max_len);
  45. if (! cmdline)
  46. return 0;
  47. while (1)
  48. {
  49. if (grub_file_read (file, &c, 1) != 1)
  50. break;
  51. /* Skip all carriage returns. */
  52. if (c == '\r')
  53. continue;
  54. if (pos + 1 >= max_len)
  55. {
  56. char *old_cmdline = cmdline;
  57. max_len = max_len * 2;
  58. cmdline = grub_realloc (cmdline, max_len);
  59. if (! cmdline)
  60. {
  61. grub_free (old_cmdline);
  62. return 0;
  63. }
  64. }
  65. if (c == '\n')
  66. {
  67. have_newline = 1;
  68. break;
  69. }
  70. cmdline[pos++] = c;
  71. }
  72. cmdline[pos] = '\0';
  73. /* If the buffer is empty, don't return anything at all. */
  74. if (pos == 0 && !have_newline)
  75. {
  76. grub_free (cmdline);
  77. cmdline = 0;
  78. }
  79. return cmdline;
  80. }