Update.
[platform/upstream/glibc.git] / iconv / skeleton.c
1 /* Skeleton for a conversion module.
2    Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Library General Public License as
8    published by the Free Software Foundation; either version 2 of the
9    License, or (at your option) any later version.
10
11    The GNU C Library 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 GNU
14    Library General Public License for more details.
15
16    You should have received a copy of the GNU Library General Public
17    License along with the GNU C Library; see the file COPYING.LIB.  If not,
18    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 /* This file can be included to provide definitions of several things
22    many modules have in common.  It can be customized using the following
23    macros:
24
25      DEFINE_INIT        define the default initializer.  This requires the
26                         following symbol to be defined.
27
28      CHARSET_NAME       string with official name of the coded character
29                         set (in all-caps)
30
31      DEFINE_FINI        define the default destructor function.
32
33      MIN_NEEDED_FROM    minimal number of bytes needed for the from-charset.
34      MIN_NEEDED_TO      likewise for the to-charset.
35
36      MAX_NEEDED_FROM    maximal number of bytes needed for the from-charset.
37                         This macro is optional, it defaults to MIN_NEEDED_FROM.
38      MAX_NEEDED_TO      likewise for the to-charset.
39
40      DEFINE_DIRECTION_OBJECTS
41                         two objects will be defined to be used when the
42                         `gconv' function must only distinguish two
43                         directions.  This is implied by DEFINE_INIT.
44                         If this macro is not defined the following
45                         macro must be available.
46
47      FROM_DIRECTION     this macro is supposed to return a value != 0
48                         if we convert from the current character set,
49                         otherwise it return 0.
50
51      EMIT_SHIFT_TO_INIT this symbol is optional.  If it is defined it
52                         defines some code which writes out a sequence
53                         of characters which bring the current state into
54                         the initial state.
55
56      FROM_LOOP          name of the function implementing the conversion
57                         from the current characters.
58      TO_LOOP            likewise for the other direction
59
60      RESET_STATE        in case of an error we must reset the state for
61                         the rerun so this macro must be defined for
62                         stateful encodings.  It takes an argument which
63                         is nonzero when saving.
64
65      RESET_INPUT_BUFFER If the input character sets allow this the macro
66                         can be defined to reset the input buffer pointers
67                         to cover only those characters up to the error.
68
69      FUNCTION_NAME      if not set the conversion function is named `gconv'.
70
71      PREPARE_LOOP       optional code preparing the conversion loop.  Can
72                         contain variable definitions.
73      END_LOOP           also optional, may be used to store information
74
75      EXTRA_LOOP_ARGS    optional macro specifying extra arguments passed
76                         to loop function.
77  */
78
79 #include <assert.h>
80 #include <gconv.h>
81 #include <string.h>
82 #define __need_size_t
83 #define __need_NULL
84 #include <stddef.h>
85
86 #ifndef STATIC_GCONV
87 # include <dlfcn.h>
88 #endif
89
90 #ifndef DL_CALL_FCT
91 # define DL_CALL_FCT(fct, args) fct args
92 #endif
93
94 /* The direction objects.  */
95 #if DEFINE_DIRECTION_OBJECTS || DEFINE_INIT
96 static int from_object;
97 static int to_object;
98
99 # ifndef FROM_DIRECTION
100 #  define FROM_DIRECTION (step->__data == &from_object)
101 # endif
102 #else
103 # ifndef FROM_DIRECTION
104 #  error "FROM_DIRECTION must be provided if direction objects are not used"
105 # endif
106 #endif
107
108
109 /* How many bytes are needed at most for the from-charset.  */
110 #ifndef MAX_NEEDED_FROM
111 # define MAX_NEEDED_FROM        MIN_NEEDED_FROM
112 #endif
113
114 /* Same for the to-charset.  */
115 #ifndef MAX_NEEDED_TO
116 # define MAX_NEEDED_TO          MIN_NEEDED_TO
117 #endif
118
119
120 /* Define macros which can access unaligned buffers.  These macros are
121    supposed to be used only in code outside the inner loops.  For the inner
122    loops we have other definitions which allow optimized access.  */
123 #ifdef _STRING_ARCH_unaligned
124 /* We can handle unaligned memory access.  */
125 # define get16u(addr) *((uint16_t *) (addr))
126 # define get32u(addr) *((uint32_t *) (addr))
127
128 /* We need no special support for writing values either.  */
129 # define put16u(addr, val) *((uint16_t *) (addr)) = (val)
130 # define put32u(addr, val) *((uint32_t *) (addr)) = (val)
131 #else
132 /* Distinguish between big endian and little endian.  */
133 # if __BYTE_ORDER == __LITTLE_ENDIAN
134 #  define get16u(addr) \
135      (((__const unsigned char *) (addr))[1] << 8                              \
136       | ((__const unsigned char *) (addr))[0])
137 #  define get32u(addr) \
138      (((((__const unsigned char *) (addr))[3] << 8                            \
139         | ((__const unsigned char *) (addr))[2]) << 8                         \
140        | ((__const unsigned char *) (addr))[1]) << 8                          \
141       | ((__const unsigned char *) (addr))[0])
142
143 #  define put16u(addr, val) \
144      ({ uint16_t __val = (val);                                               \
145         ((unsigned char *) (addr))[0] = __val;                                \
146         ((unsigned char *) (addr))[1] = __val >> 8;                           \
147         (void) 0; })
148 #  define put32u(addr, val) \
149      ({ uint32_t __val = (val);                                               \
150         ((unsigned char *) (addr))[0] = __val;                                \
151         __val >>= 8;                                                          \
152         ((unsigned char *) (addr))[1] = __val;                                \
153         __val >>= 8;                                                          \
154         ((unsigned char *) (addr))[2] = __val;                                \
155         __val >>= 8;                                                          \
156         ((unsigned char *) (addr))[3] = __val;                                \
157         (void) 0; })
158 # else
159 #  define get16u(addr) \
160      (((__const unsigned char *) (addr))[0] << 8                              \
161       | ((__const unsigned char *) (addr))[1])
162 #  define get32u(addr) \
163      (((((__const unsigned char *) (addr))[0] << 8                            \
164         | ((__const unsigned char *) (addr))[1]) << 8                         \
165        | ((__const unsigned char *) (addr))[2]) << 8                          \
166       | ((__const unsigned char *) (addr))[3])
167
168 #  define put16u(addr, val) \
169      ({ uint16_t __val = (val);                                               \
170         ((unsigned char *) (addr))[1] = __val;                                \
171         ((unsigned char *) (addr))[0] = __val >> 8;                           \
172         (void) 0; })
173 #  define put32u(addr, val) \
174      ({ uint32_t __val = (val);                                               \
175         ((unsigned char *) (addr))[3] = __val;                                \
176         __val >>= 8;                                                          \
177         ((unsigned char *) (addr))[2] = __val;                                \
178         __val >>= 8;                                                          \
179         ((unsigned char *) (addr))[1] = __val;                                \
180         __val >>= 8;                                                          \
181         ((unsigned char *) (addr))[0] = __val;                                \
182         (void) 0; })
183 # endif
184 #endif
185
186
187 /* For conversions from a fixed width character sets to another fixed width
188    character set we we can define RESET_INPUT_BUFFER is necessary.  */
189 #if !defined RESET_INPUT_BUFFER && !defined SAVE_RESET_STATE
190 # if MIN_NEEDED_FROM == MAX_NEEDED_FROM && MIN_NEEDED_TO == MAX_NEEDED_TO
191 /* We have to use these `if's here since the compiler cannot know that
192    (outbuf - outerr) is always divisible by MIN_NEEDED_TO.  */
193 #  define RESET_INPUT_BUFFER \
194   if (MIN_NEEDED_FROM % MIN_NEEDED_TO == 0)                                   \
195     *inptrp -= (outbuf - outerr) * (MIN_NEEDED_FROM / MIN_NEEDED_TO);         \
196   else if (MIN_NEEDED_TO % MIN_NEEDED_FROM == 0)                              \
197     *inptrp -= (outbuf - outerr) / (MIN_NEEDED_TO / MIN_NEEDED_FROM);         \
198   else                                                                        \
199     *inptrp -= ((outbuf - outerr) / MIN_NEEDED_TO) * MIN_NEEDED_FROM
200 # endif
201 #endif
202
203
204 /* The default init function.  It simply matches the name and initializes
205    the step data to point to one of the objects above.  */
206 #if DEFINE_INIT
207 # ifndef CHARSET_NAME
208 #  error "CHARSET_NAME not defined"
209 # endif
210
211 int
212 gconv_init (struct __gconv_step *step)
213 {
214   /* Determine which direction.  */
215   if (strcmp (step->__from_name, CHARSET_NAME) == 0)
216     {
217       step->__data = &from_object;
218
219       step->__min_needed_from = MIN_NEEDED_FROM;
220       step->__max_needed_from = MAX_NEEDED_FROM;
221       step->__min_needed_to = MIN_NEEDED_TO;
222       step->__max_needed_to = MAX_NEEDED_TO;
223     }
224   else if (__builtin_expect (strcmp (step->__to_name, CHARSET_NAME), 0) == 0)
225     {
226       step->__data = &to_object;
227
228       step->__min_needed_from = MIN_NEEDED_TO;
229       step->__max_needed_from = MAX_NEEDED_TO;
230       step->__min_needed_to = MIN_NEEDED_FROM;
231       step->__max_needed_to = MAX_NEEDED_FROM;
232     }
233   else
234     return __GCONV_NOCONV;
235
236 #ifdef RESET_STATE
237   step->__stateful = 1;
238 #else
239   step->__stateful = 0;
240 #endif
241
242   return __GCONV_OK;
243 }
244 #endif
245
246
247 /* The default destructor function does nothing in the moment and so
248    be define it at all.  But we still provide the macro just in case
249    we need it some day.  */
250 #if DEFINE_FINI
251 #endif
252
253
254 /* If no arguments have to passed to the loop function define the macro
255    as empty.  */
256 #ifndef EXTRA_LOOP_ARGS
257 # define EXTRA_LOOP_ARGS
258 #endif
259
260
261 /* This is the actual conversion function.  */
262 #ifndef FUNCTION_NAME
263 # define FUNCTION_NAME  gconv
264 #endif
265
266 /* The macros are used to access the function to convert single characters.  */
267 #define SINGLE(fct) SINGLE2 (fct)
268 #define SINGLE2(fct) fct##_single
269
270
271 int
272 FUNCTION_NAME (struct __gconv_step *step, struct __gconv_step_data *data,
273                const unsigned char **inptrp, const unsigned char *inend,
274                unsigned char *outbufstart, size_t *irreversible, int do_flush,
275                int consume_incomplete)
276 {
277   struct __gconv_step *next_step = step + 1;
278   struct __gconv_step_data *next_data = data + 1;
279   __gconv_fct fct;
280   int status;
281
282   fct = (data->__flags & __GCONV_IS_LAST) ? NULL : next_step->__fct;
283
284   /* If the function is called with no input this means we have to reset
285      to the initial state.  The possibly partly converted input is
286      dropped.  */
287   if (__builtin_expect (do_flush, 0))
288     {
289       status = __GCONV_OK;
290
291 #ifdef EMIT_SHIFT_TO_INIT
292       /* Emit the escape sequence to reset the state.  */
293       EMIT_SHIFT_TO_INIT;
294 #endif
295       /* Call the steps down the chain if there are any but only if we
296          successfully emitted the escape sequence.  */
297       if (status == __GCONV_OK && ! (data->__flags & __GCONV_IS_LAST))
298         status = DL_CALL_FCT (fct, (next_step, next_data, NULL, NULL,
299                                     next_data->__outbuf, irreversible, 1,
300                                     consume_incomplete));
301     }
302   else
303     {
304       /* We preserve the initial values of the pointer variables.  */
305       const unsigned char *inptr = *inptrp;
306       unsigned char *outbuf = outbufstart;
307       unsigned char *outend = data->__outbufend;
308       unsigned char *outstart;
309       /* This variable is used to count the number of characters we
310          actually converted.  */
311       size_t lirreversible = 0;
312 #if defined _STRING_ARCH_unaligned \
313     || MIN_NEEDED_FROM == 1 || MAX_NEEDED_FROM % MIN_NEEDED_FROM != 0 \
314     || MIN_NEEDED_TO == 1 || MAX_NEEDED_TO % MIN_NEEDED_TO != 0
315 # define unaligned 0
316 #else
317       int unaligned;
318 # define GEN_unaligned(name) GEN_unaligned2 (name)
319 # define GEN_unaligned2(name) name##_unaligned
320 #endif
321
322 #ifdef PREPARE_LOOP
323       PREPARE_LOOP
324 #endif
325
326 #if MAX_NEEDED_FROM > 1 || MAX_NEEDED_TO > 1
327       /* If the function is used to implement the mb*towc*() or wc*tomb*()
328          functions we must test whether any bytes from the last call are
329          stored in the `state' object.  */
330       if (((MAX_NEEDED_FROM > 1 && FROM_DIRECTION)
331            || (MAX_NEEDED_TO > 1 && !FROM_DIRECTION))
332           && consume_incomplete && (data->__statep->__count & 7) != 0)
333         {
334           /* Yep, we have some bytes left over.  Process them now.  */
335
336 # if MAX_NEEDED_FROM > 1
337           if (MAX_NEEDED_TO == 1 || FROM_DIRECTION)
338             status = SINGLE(FROM_LOOP) (step, data, inptrp, inend, &outbuf,
339                                         outend, &lirreversible
340                                         EXTRA_LOOP_ARGS);
341 # endif
342 # if MAX_NEEDED_FROM > 1 && MAX_NEEDED_TO > 1 && !ONE_DIRECTION
343           else
344 # endif
345 # if MAX_NEEDED_TO > 1 && !ONE_DIRECTION
346             status = SINGLE(TO_LOOP) (step, data, inptrp, inend, &outbuf,
347                                       outend, &lirreversible EXTRA_LOOP_ARGS);
348 # endif
349
350           if (__builtin_expect (status, __GCONV_OK) != __GCONV_OK)
351             return status;
352         }
353 #endif
354
355 #if !defined _STRING_ARCH_unaligned \
356     && MIN_NEEDED_FROM != 1 && MAX_NEEDED_FROM % MIN_NEEDED_FROM == 0 \
357     && MIN_NEEDED_TO != 1 && MAX_NEEDED_TO % MIN_NEEDED_TO == 0
358       /* The following assumes that encodings, which have a variable length
359          what might unalign a buffer even though it is a aligned in the
360          beginning, either don't have the minimal number of bytes as a divisor
361          of the maximum length or have a minimum length of 1.  This is true
362          for all known and supported encodings.  */
363       unaligned = ((FROM_DIRECTION
364                     && ((uintptr_t) inptr % MIN_NEEDED_FROM != 0
365                         || ((data->__flags & __GCONV_IS_LAST)
366                             && (uintptr_t) outbuf % MIN_NEEDED_TO != 0)))
367                    || (!FROM_DIRECTION
368                        && (((data->__flags & __GCONV_IS_LAST)
369                             && (uintptr_t) outbuf % MIN_NEEDED_FROM != 0)
370                            || (uintptr_t) inptr % MIN_NEEDED_TO != 0)));
371 #endif
372
373       do
374         {
375           /* Remember the start value for this round.  */
376           inptr = *inptrp;
377           /* The outbuf buffer is empty.  */
378           outstart = outbuf;
379
380 #ifdef SAVE_RESET_STATE
381           SAVE_RESET_STATE (1);
382 #endif
383
384           if (__builtin_expect (!unaligned, 1))
385             {
386               if (FROM_DIRECTION)
387                 /* Run the conversion loop.  */
388                 status = FROM_LOOP (step, data, inptrp, inend, &outbuf, outend,
389                                     &lirreversible EXTRA_LOOP_ARGS);
390               else
391                 /* Run the conversion loop.  */
392                 status = TO_LOOP (step, data, inptrp, inend, &outbuf, outend,
393                                   &lirreversible EXTRA_LOOP_ARGS);
394             }
395 #if !defined _STRING_ARCH_unaligned \
396     && MIN_NEEDED_FROM != 1 && MAX_NEEDED_FROM % MIN_NEEDED_FROM == 0 \
397     && MIN_NEEDED_TO != 1 && MAX_NEEDED_TO % MIN_NEEDED_TO == 0
398           else
399             {
400               if (FROM_DIRECTION)
401                 /* Run the conversion loop.  */
402                 status = GEN_unaligned (FROM_LOOP) (step, data, inptrp, inend,
403                                                     &outbuf, outend,
404                                                     &lirreversible
405                                                     EXTRA_LOOP_ARGS);
406               else
407                 /* Run the conversion loop.  */
408                 status = GEN_unaligned (TO_LOOP) (step, data, inptrp, inend,
409                                                   &outbuf, outend,
410                                                   &lirreversible
411                                                   EXTRA_LOOP_ARGS);
412             }
413 #endif
414
415           /* We finished one use of the loops.  */
416           ++data->__invocation_counter;
417
418           /* If this is the last step leave the loop, there is nothing
419              we can do.  */
420           if (__builtin_expect (data->__flags & __GCONV_IS_LAST, 0))
421             {
422               /* Store information about how many bytes are available.  */
423               data->__outbuf = outbuf;
424
425               /* Remember how many non-identical characters we
426                  converted in a irreversible way.  */
427               *irreversible += lirreversible;
428
429               break;
430             }
431
432           /* Write out all output which was produced.  */
433           if (__builtin_expect (outbuf > outstart, 1))
434             {
435               const unsigned char *outerr = data->__outbuf;
436               int result;
437
438               result = DL_CALL_FCT (fct, (next_step, next_data, &outerr,
439                                           outbuf, next_data->__outbuf,
440                                           irreversible, 0,
441                                           consume_incomplete));
442
443               if (result != __GCONV_EMPTY_INPUT)
444                 {
445                   if (__builtin_expect (outerr != outbuf, 0))
446                     {
447 #ifdef RESET_INPUT_BUFFER
448                       RESET_INPUT_BUFFER;
449 #else
450                       /* We have a problem with the in on of the functions
451                          below.  Undo the conversion upto the error point.  */
452                       size_t nstatus;
453
454                       /* Reload the pointers.  */
455                       *inptrp = inptr;
456                       outbuf = outstart;
457
458                       /* Reset the state.  */
459 # ifdef SAVE_RESET_STATE
460                       SAVE_RESET_STATE (0);
461 # endif
462
463                       /* XXX Handle unaligned access here as well.  */
464                       if (FROM_DIRECTION)
465                         /* Run the conversion loop.  */
466                         nstatus = FROM_LOOP (step, data,
467                                              (const unsigned char **) inptrp,
468                                              (const unsigned char *) inend,
469                                              (unsigned char **) &outbuf,
470                                              (unsigned char *) outerr,
471                                              &lirreversible EXTRA_LOOP_ARGS);
472                       else
473                         /* Run the conversion loop.  */
474                         nstatus = TO_LOOP (step, data,
475                                            (const unsigned char **) inptrp,
476                                            (const unsigned char *) inend,
477                                            (unsigned char **) &outbuf,
478                                            (unsigned char *) outerr,
479                                            &lirreversible EXTRA_LOOP_ARGS);
480
481                       /* We must run out of output buffer space in this
482                          rerun.  */
483                       assert (outbuf == outerr);
484                       assert (nstatus == __GCONV_FULL_OUTPUT);
485
486                       /* If we haven't consumed a single byte decrement
487                          the invocation counter.  */
488                       if (__builtin_expect (outbuf == outstart, 0))
489                         --data->__invocation_counter;
490 #endif  /* reset input buffer */
491                     }
492
493                   /* Change the status.  */
494                   status = result;
495                 }
496               else
497                 /* All the output is consumed, we can make another run
498                    if everything was ok.  */
499                 if (status == __GCONV_FULL_OUTPUT)
500                   status = __GCONV_OK;
501             }
502         }
503       while (status == __GCONV_OK);
504
505 #ifdef END_LOOP
506       END_LOOP
507 #endif
508
509       /* If we are supposed to consume all character store now all of the
510          remaining characters in the `state' object.  */
511 #if MAX_NEEDED_FROM > 1 || MAX_NEEDED_TO > 1
512       if (((MAX_NEEDED_FROM > 1 && FROM_DIRECTION)
513            || (MAX_NEEDED_TO > 1 && !FROM_DIRECTION))
514           && __builtin_expect (consume_incomplete, 0)
515           && status == __GCONV_INCOMPLETE_INPUT)
516         {
517 # ifdef STORE_REST
518           mbstate_t *state = data->__statep;
519
520           STORE_REST
521 # else
522           size_t cnt;
523
524           /* Make sure the remaining bytes fit into the state objects
525              buffer.  */
526           assert (inend - *inptrp < 4);
527
528           for (cnt = 0; *inptrp < inend; ++cnt)
529             data->__statep->__value.__wchb[cnt] = *(*inptrp)++;
530           data->__statep->__count &= ~7;
531           data->__statep->__count |= cnt;
532 # endif
533         }
534 #endif
535     }
536
537   return status;
538 }
539
540 #undef DEFINE_INIT
541 #undef CHARSET_NAME
542 #undef DEFINE_FINI
543 #undef MIN_NEEDED_FROM
544 #undef MIN_NEEDED_TO
545 #undef MAX_NEEDED_FROM
546 #undef MAX_NEEDED_TO
547 #undef DEFINE_DIRECTION_OBJECTS
548 #undef FROM_DIRECTION
549 #undef EMIT_SHIFT_TO_INIT
550 #undef FROM_LOOP
551 #undef TO_LOOP
552 #undef RESET_STATE
553 #undef RESET_INPUT_BUFFER
554 #undef FUNCTION_NAME
555 #undef PREPARE_LOOP
556 #undef END_LOOP
557 #undef ONE_DIRECTION
558 #undef STORE_REST