iconv_charmap.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /* Convert using charmaps and possibly iconv().
  2. Copyright (C) 2001-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published
  6. by the Free Software Foundation; version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, see <https://www.gnu.org/licenses/>. */
  14. #include <assert.h>
  15. #include <errno.h>
  16. #include <error.h>
  17. #include <fcntl.h>
  18. #include <iconv.h>
  19. #include <libintl.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #include <stdint.h>
  24. #include <sys/mman.h>
  25. #include <sys/stat.h>
  26. #include "iconv_prog.h"
  27. /* Prototypes for a few program-wide used functions. */
  28. #include <programs/xmalloc.h>
  29. struct convtable
  30. {
  31. int term[256 / 8];
  32. union
  33. {
  34. struct convtable *sub;
  35. struct charseq *out;
  36. } val[256];
  37. };
  38. static inline struct convtable *
  39. allocate_table (void)
  40. {
  41. return (struct convtable *) xcalloc (1, sizeof (struct convtable));
  42. }
  43. static inline void
  44. free_table (struct convtable *tbl)
  45. {
  46. free (tbl);
  47. }
  48. static inline int
  49. is_term (struct convtable *tbl, unsigned int idx)
  50. {
  51. return tbl->term[idx / 8] & (1 << (idx % 8));
  52. }
  53. static inline void
  54. clear_term (struct convtable *tbl, unsigned int idx)
  55. {
  56. tbl->term[idx / 8] &= ~(1 << (idx % 8));
  57. }
  58. static inline void
  59. set_term (struct convtable *tbl, unsigned int idx)
  60. {
  61. tbl->term[idx / 8] |= 1 << (idx % 8);
  62. }
  63. /* Generate the conversion table. */
  64. static struct convtable *use_from_charmap (struct charmap_t *from_charmap,
  65. const char *to_code);
  66. static struct convtable *use_to_charmap (const char *from_code,
  67. struct charmap_t *to_charmap);
  68. static struct convtable *use_both_charmaps (struct charmap_t *from_charmap,
  69. struct charmap_t *to_charmap);
  70. /* Prototypes for the functions doing the actual work. */
  71. static int process_block (struct convtable *tbl, char *addr, size_t len,
  72. FILE *output);
  73. static int process_fd (struct convtable *tbl, int fd, FILE *output);
  74. static int process_file (struct convtable *tbl, FILE *input, FILE *output);
  75. int
  76. charmap_conversion (const char *from_code, struct charmap_t *from_charmap,
  77. const char *to_code, struct charmap_t *to_charmap,
  78. int argc, int remaining, char *argv[],
  79. const char *output_file)
  80. {
  81. struct convtable *cvtbl;
  82. int status = EXIT_SUCCESS;
  83. /* We have three different cases to handle:
  84. - both, from_charmap and to_charmap, are available. This means we
  85. can assume that the symbolic names match and use them to create
  86. the mapping.
  87. - only from_charmap is available. In this case we can only hope that
  88. the symbolic names used are of the <Uxxxx> form in which case we
  89. can use a UCS4->"to_code" iconv() conversion for the second step.
  90. - only to_charmap is available. This is similar, only that we would
  91. use iconv() for the "to_code"->UCS4 conversion.
  92. We first create a table which maps input bytes into output bytes.
  93. Once this is done we can handle all three of the cases above
  94. equally. */
  95. if (from_charmap != NULL)
  96. {
  97. if (to_charmap == NULL)
  98. cvtbl = use_from_charmap (from_charmap, to_code);
  99. else
  100. cvtbl = use_both_charmaps (from_charmap, to_charmap);
  101. }
  102. else
  103. {
  104. assert (to_charmap != NULL);
  105. cvtbl = use_to_charmap (from_code, to_charmap);
  106. }
  107. /* If we couldn't generate a table stop now. */
  108. if (cvtbl == NULL)
  109. return EXIT_FAILURE;
  110. /* Determine output file. */
  111. FILE *output;
  112. if (output_file != NULL && strcmp (output_file, "-") != 0)
  113. {
  114. output = fopen (output_file, "w");
  115. if (output == NULL)
  116. error (EXIT_FAILURE, errno, _("cannot open output file"));
  117. }
  118. else
  119. output = stdout;
  120. /* We can now start the conversion. */
  121. if (remaining == argc)
  122. {
  123. if (process_file (cvtbl, stdin, output) != 0)
  124. status = EXIT_FAILURE;
  125. }
  126. else
  127. do
  128. {
  129. int fd;
  130. if (verbose)
  131. printf ("%s:\n", argv[remaining]);
  132. if (strcmp (argv[remaining], "-") == 0)
  133. fd = 0;
  134. else
  135. {
  136. fd = open (argv[remaining], O_RDONLY);
  137. if (fd == -1)
  138. {
  139. error (0, errno, _("cannot open input file `%s'"),
  140. argv[remaining]);
  141. status = EXIT_FAILURE;
  142. continue;
  143. }
  144. }
  145. #ifdef _POSIX_MAPPED_FILES
  146. struct stat64 st;
  147. char *addr;
  148. /* We have possibilities for reading the input file. First try
  149. to mmap() it since this will provide the fastest solution. */
  150. if (fstat64 (fd, &st) == 0
  151. && ((addr = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE,
  152. fd, 0)) != MAP_FAILED))
  153. {
  154. /* Yes, we can use mmap(). The descriptor is not needed
  155. anymore. */
  156. if (close (fd) != 0)
  157. error (EXIT_FAILURE, errno,
  158. _("error while closing input `%s'"), argv[remaining]);
  159. if (process_block (cvtbl, addr, st.st_size, output) < 0)
  160. {
  161. /* Something went wrong. */
  162. status = EXIT_FAILURE;
  163. /* We don't need the input data anymore. */
  164. munmap ((void *) addr, st.st_size);
  165. /* We cannot go on with producing output since it might
  166. lead to problem because the last output might leave
  167. the output stream in an undefined state. */
  168. break;
  169. }
  170. /* We don't need the input data anymore. */
  171. munmap ((void *) addr, st.st_size);
  172. }
  173. else
  174. #endif /* _POSIX_MAPPED_FILES */
  175. {
  176. /* Read the file in pieces. */
  177. if (process_fd (cvtbl, fd, output) != 0)
  178. {
  179. /* Something went wrong. */
  180. status = EXIT_FAILURE;
  181. /* We don't need the input file anymore. */
  182. close (fd);
  183. /* We cannot go on with producing output since it might
  184. lead to problem because the last output might leave
  185. the output stream in an undefined state. */
  186. break;
  187. }
  188. /* Now close the file. */
  189. close (fd);
  190. }
  191. }
  192. while (++remaining < argc);
  193. /* All done. */
  194. if (output != stdout)
  195. fclose (output);
  196. free_table (cvtbl);
  197. return status;
  198. }
  199. /* Add the IN->OUT mapping to TBL. OUT is potentially stored in the table.
  200. IN is used only here, so it need not be kept live afterwards. */
  201. static void
  202. add_bytes (struct convtable *tbl, const struct charseq *in, struct charseq *out)
  203. {
  204. int n = 0;
  205. unsigned int byte;
  206. assert (in->nbytes > 0);
  207. byte = ((unsigned char *) in->bytes)[n];
  208. while (n + 1 < in->nbytes)
  209. {
  210. if (is_term (tbl, byte) || tbl->val[byte].sub == NULL)
  211. {
  212. /* Note that we simply ignore a definition for a byte sequence
  213. which is also the prefix for a longer one. */
  214. clear_term (tbl, byte);
  215. tbl->val[byte].sub =
  216. (struct convtable *) xcalloc (1, sizeof (struct convtable));
  217. }
  218. tbl = tbl->val[byte].sub;
  219. byte = ((unsigned char *) in->bytes)[++n];
  220. }
  221. /* Only add the new sequence if there is none yet and the byte sequence
  222. is not part of an even longer one. */
  223. if (! is_term (tbl, byte) && tbl->val[byte].sub == NULL)
  224. {
  225. set_term (tbl, byte);
  226. tbl->val[byte].out = out;
  227. }
  228. }
  229. /* Try to convert SEQ from WCHAR_T format using CD.
  230. Returns a malloc'd struct or NULL. */
  231. static struct charseq *
  232. convert_charseq (iconv_t cd, const struct charseq *seq)
  233. {
  234. struct charseq *result = NULL;
  235. if (seq->ucs4 != UNINITIALIZED_CHAR_VALUE)
  236. {
  237. /* There is a chance. Try the iconv module. */
  238. wchar_t inbuf[1] = { seq->ucs4 };
  239. unsigned char outbuf[64];
  240. char *inptr = (char *) inbuf;
  241. size_t inlen = sizeof (inbuf);
  242. char *outptr = (char *) outbuf;
  243. size_t outlen = sizeof (outbuf);
  244. (void) iconv (cd, &inptr, &inlen, &outptr, &outlen);
  245. if (outptr != (char *) outbuf)
  246. {
  247. /* We got some output. Good, use it. */
  248. outlen = sizeof (outbuf) - outlen;
  249. assert ((char *) outbuf + outlen == outptr);
  250. result = xmalloc (sizeof (struct charseq) + outlen);
  251. result->name = seq->name;
  252. result->ucs4 = seq->ucs4;
  253. result->nbytes = outlen;
  254. memcpy (result->bytes, outbuf, outlen);
  255. }
  256. /* Clear any possible state left behind. */
  257. (void) iconv (cd, NULL, NULL, NULL, NULL);
  258. }
  259. return result;
  260. }
  261. static struct convtable *
  262. use_from_charmap (struct charmap_t *from_charmap, const char *to_code)
  263. {
  264. /* We iterate over all entries in the from_charmap and for those which
  265. have a known UCS4 representation we use an iconv() call to determine
  266. the mapping to the to_code charset. */
  267. struct convtable *rettbl;
  268. iconv_t cd;
  269. void *ptr = NULL;
  270. const void *key;
  271. size_t keylen;
  272. void *data;
  273. cd = iconv_open (to_code, "WCHAR_T");
  274. if (cd == (iconv_t) -1)
  275. /* We cannot do anything. */
  276. return NULL;
  277. rettbl = allocate_table ();
  278. while (iterate_table (&from_charmap->char_table, &ptr, &key, &keylen, &data)
  279. >= 0)
  280. {
  281. struct charseq *in = data;
  282. struct charseq *newp = convert_charseq (cd, in);
  283. if (newp != NULL)
  284. add_bytes (rettbl, in, newp);
  285. }
  286. iconv_close (cd);
  287. return rettbl;
  288. }
  289. static struct convtable *
  290. use_to_charmap (const char *from_code, struct charmap_t *to_charmap)
  291. {
  292. /* We iterate over all entries in the to_charmap and for those which
  293. have a known UCS4 representation we use an iconv() call to determine
  294. the mapping to the from_code charset. */
  295. struct convtable *rettbl;
  296. iconv_t cd;
  297. void *ptr = NULL;
  298. const void *key;
  299. size_t keylen;
  300. void *data;
  301. /* Note that the conversion we use here is the reverse direction. Without
  302. exhaustive search we cannot figure out which input yields the UCS4
  303. character we are looking for. Therefore we determine it the other
  304. way round. */
  305. cd = iconv_open (from_code, "WCHAR_T");
  306. if (cd == (iconv_t) -1)
  307. /* We cannot do anything. */
  308. return NULL;
  309. rettbl = allocate_table ();
  310. while (iterate_table (&to_charmap->char_table, &ptr, &key, &keylen, &data)
  311. >= 0)
  312. {
  313. struct charseq *out = data;
  314. struct charseq *newp = convert_charseq (cd, out);
  315. if (newp != NULL)
  316. {
  317. add_bytes (rettbl, newp, out);
  318. free (newp);
  319. }
  320. }
  321. iconv_close (cd);
  322. return rettbl;
  323. }
  324. static struct convtable *
  325. use_both_charmaps (struct charmap_t *from_charmap,
  326. struct charmap_t *to_charmap)
  327. {
  328. /* In this case we iterate over all the entries in the from_charmap,
  329. determine the internal name, and find an appropriate entry in the
  330. to_charmap (if it exists). */
  331. struct convtable *rettbl = allocate_table ();
  332. void *ptr = NULL;
  333. const void *key;
  334. size_t keylen;
  335. void *data;
  336. while (iterate_table (&from_charmap->char_table, &ptr, &key, &keylen, &data)
  337. >= 0)
  338. {
  339. struct charseq *in = (struct charseq *) data;
  340. struct charseq *out = charmap_find_value (to_charmap, key, keylen);
  341. if (out != NULL)
  342. add_bytes (rettbl, in, out);
  343. }
  344. return rettbl;
  345. }
  346. static int
  347. process_block (struct convtable *tbl, char *addr, size_t len, FILE *output)
  348. {
  349. size_t n = 0;
  350. while (n < len)
  351. {
  352. struct convtable *cur = tbl;
  353. unsigned char *curp = (unsigned char *) addr;
  354. unsigned int byte = *curp;
  355. int cnt;
  356. struct charseq *out;
  357. while (! is_term (cur, byte))
  358. if (cur->val[byte].sub == NULL)
  359. {
  360. /* This is an invalid sequence. Skip the first byte if we are
  361. ignoring errors. Otherwise punt. */
  362. if (! omit_invalid)
  363. {
  364. error (0, 0, _("illegal input sequence at position %zd"), n);
  365. return -1;
  366. }
  367. n -= curp - (unsigned char *) addr;
  368. byte = *(curp = (unsigned char *) ++addr);
  369. if (++n >= len)
  370. /* All converted. */
  371. return 0;
  372. cur = tbl;
  373. }
  374. else
  375. {
  376. cur = cur->val[byte].sub;
  377. if (++n >= len)
  378. {
  379. error (0, 0, _("\
  380. incomplete character or shift sequence at end of buffer"));
  381. return -1;
  382. }
  383. byte = *++curp;
  384. }
  385. /* We found a final byte. Write the output bytes. */
  386. out = cur->val[byte].out;
  387. for (cnt = 0; cnt < out->nbytes; ++cnt)
  388. fputc_unlocked (out->bytes[cnt], output);
  389. addr = (char *) curp + 1;
  390. ++n;
  391. }
  392. return 0;
  393. }
  394. static int
  395. process_fd (struct convtable *tbl, int fd, FILE *output)
  396. {
  397. /* We have a problem with reading from a descriptor since we must not
  398. provide the iconv() function an incomplete character or shift
  399. sequence at the end of the buffer. Since we have to deal with
  400. arbitrary encodings we must read the whole text in a buffer and
  401. process it in one step. */
  402. static char *inbuf = NULL;
  403. static size_t maxlen = 0;
  404. char *inptr = inbuf;
  405. size_t actlen = 0;
  406. while (actlen < maxlen)
  407. {
  408. ssize_t n = read (fd, inptr, maxlen - actlen);
  409. if (n == 0)
  410. /* No more text to read. */
  411. break;
  412. if (n == -1)
  413. {
  414. /* Error while reading. */
  415. error (0, errno, _("error while reading the input"));
  416. return -1;
  417. }
  418. inptr += n;
  419. actlen += n;
  420. }
  421. if (actlen == maxlen)
  422. while (1)
  423. {
  424. ssize_t n;
  425. char *new_inbuf;
  426. /* Increase the buffer. */
  427. new_inbuf = (char *) realloc (inbuf, maxlen + 32768);
  428. if (new_inbuf == NULL)
  429. {
  430. error (0, errno, _("unable to allocate buffer for input"));
  431. return -1;
  432. }
  433. inbuf = new_inbuf;
  434. maxlen += 32768;
  435. inptr = inbuf + actlen;
  436. do
  437. {
  438. n = read (fd, inptr, maxlen - actlen);
  439. if (n == 0)
  440. /* No more text to read. */
  441. break;
  442. if (n == -1)
  443. {
  444. /* Error while reading. */
  445. error (0, errno, _("error while reading the input"));
  446. return -1;
  447. }
  448. inptr += n;
  449. actlen += n;
  450. }
  451. while (actlen < maxlen);
  452. if (n == 0)
  453. /* Break again so we leave both loops. */
  454. break;
  455. }
  456. /* Now we have all the input in the buffer. Process it in one run. */
  457. return process_block (tbl, inbuf, actlen, output);
  458. }
  459. static int
  460. process_file (struct convtable *tbl, FILE *input, FILE *output)
  461. {
  462. /* This should be safe since we use this function only for `stdin' and
  463. we haven't read anything so far. */
  464. return process_fd (tbl, fileno (input), output);
  465. }