Hexstring.cc 70.9 KB
Newer Older
Elemer Lelik's avatar
Elemer Lelik committed
1
/******************************************************************************
Adam Knapp's avatar
Adam Knapp committed
2
 * Copyright (c) 2000-2021 Ericsson Telecom AB
Elemer Lelik's avatar
Elemer Lelik committed
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v2.0
Elemer Lelik's avatar
Elemer Lelik committed
5
 * which accompanies this distribution, and is available at
6
 * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
Elemer Lelik's avatar
Elemer Lelik committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 *
 * Contributors:
 *   
 *   Baji, Laszlo
 *   Balasko, Jeno
 *   Baranyi, Botond
 *   Beres, Szabolcs
 *   Delic, Adam
 *   Forstner, Matyas
 *   Kovacs, Ferenc
 *   Raduly, Csaba
 *   Szabados, Kristof
 *   Szabo, Bence Janos
 *   Szabo, Janos Zoltan – initial implementation
 *   Szalai, Gabor
 *   Tatarka, Gabor
 *
 ******************************************************************************/
Elemer Lelik's avatar
Elemer Lelik committed
25
26
27
28
29
30
31
32
33
34
#include "Hexstring.hh"
#include "../common/memory.h"
#include "Integer.hh"
#include "String_struct.hh"
#include "Param_Types.hh"
#include "Error.hh"
#include "Logger.hh"
#include "Encdec.hh"
#include "RAW.hh"
#include "Addfunc.hh"
35
#include "Optional.hh"
Elemer Lelik's avatar
Elemer Lelik committed
36
37
38
39

#include "../common/dbgnew.hh"

#include <string.h>
40
#include <ctype.h>
Elemer Lelik's avatar
Elemer Lelik committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425

// hexstring value class

/** The amount of memory needed for a string containing n hexadecimal digits. */
#define MEMORY_SIZE(n) (sizeof(hexstring_struct) - sizeof(int) + ((n) + 1) / 2)

void HEXSTRING::init_struct(int n_nibbles)
{
  if (n_nibbles < 0) {
    val_ptr = NULL;
    TTCN_error("Initializing an hexstring with a negative length.");
  }
  else if (n_nibbles == 0) {
    /** This will represent the empty strings so they won't need allocated
     * memory, this delays the memory allocation until it is really needed.
     */
    static hexstring_struct empty_string = { 1, 0, "" };
    val_ptr = &empty_string;
    empty_string.ref_count++;
  }
  else {
    val_ptr = (hexstring_struct*) Malloc(MEMORY_SIZE(n_nibbles));
    val_ptr->ref_count = 1;
    val_ptr->n_nibbles = n_nibbles;
  }
}

/** Return the nibble at index i
 *
 * @param nibble_index
 * @return
 */
unsigned char HEXSTRING::get_nibble(int nibble_index) const
{
  unsigned char octet = val_ptr->nibbles_ptr[nibble_index / 2];
  if (nibble_index % 2)
    return octet >> 4;   // odd  nibble -> top
  else
    return octet & 0x0F; // even nibble -> bottom
}

void HEXSTRING::set_nibble(int nibble_index, unsigned char new_value)
{
  unsigned char old_octet = val_ptr->nibbles_ptr[nibble_index / 2];
  if (nibble_index % 2) {
    val_ptr->nibbles_ptr[nibble_index / 2] = (old_octet & 0x0F) | (new_value
      << 4);
  }
  else {
    val_ptr->nibbles_ptr[nibble_index / 2] = (old_octet & 0xF0) | (new_value
      & 0x0F);
  }
}

void HEXSTRING::copy_value()
{
  if (val_ptr == NULL || val_ptr->n_nibbles <= 0) TTCN_error(
    "Internal error: Invalid internal data structure when copying "
      "the memory area of a hexstring value.");
  if (val_ptr->ref_count > 1) {
    hexstring_struct *old_ptr = val_ptr;
    old_ptr->ref_count--;
    init_struct(old_ptr->n_nibbles);
    memcpy(val_ptr->nibbles_ptr, old_ptr->nibbles_ptr, (old_ptr->n_nibbles + 1)
      / 2);
  }
}

void HEXSTRING::clear_unused_nibble() const
{
  if (val_ptr->n_nibbles % 2) val_ptr->nibbles_ptr[val_ptr->n_nibbles / 2]
    &= 0x0F;
}

HEXSTRING::HEXSTRING(int n_nibbles)
{
  init_struct(n_nibbles);
}

HEXSTRING::HEXSTRING()
{
  val_ptr = NULL;
}

HEXSTRING::HEXSTRING(int init_n_nibbles, const unsigned char* init_nibbles)
{
  init_struct(init_n_nibbles);
  memcpy(val_ptr->nibbles_ptr, init_nibbles, (init_n_nibbles + 1) / 2);
  clear_unused_nibble();
}

HEXSTRING::HEXSTRING(const HEXSTRING& other_value) :
  Base_Type(other_value)
{
  other_value.must_bound("Initialization from an unbound hexstring value.");
  val_ptr = other_value.val_ptr;
  val_ptr->ref_count++;
}

HEXSTRING::HEXSTRING(const HEXSTRING_ELEMENT& other_value)
{
  other_value.must_bound("Initialization from an unbound hexstring element.");
  init_struct(1);
  val_ptr->nibbles_ptr[0] = other_value.get_nibble();
}

HEXSTRING::~HEXSTRING()
{
  clean_up();
}

void HEXSTRING::clean_up()
{
  if (val_ptr != NULL) {
    if (val_ptr->ref_count > 1)
      val_ptr->ref_count--;
    else if (val_ptr->ref_count == 1)
      Free(val_ptr);
    else
      TTCN_error("Internal error: Invalid reference counter in a hexstring "
        "value.");
    val_ptr = NULL;
  }
}

HEXSTRING& HEXSTRING::operator=(const HEXSTRING& other_value)
{
  other_value.must_bound("Assignment of an unbound hexstring value.");
  if (&other_value != this) {
    clean_up();
    val_ptr = other_value.val_ptr;
    val_ptr->ref_count++;
  }
  return *this;
}

HEXSTRING& HEXSTRING::operator=(const HEXSTRING_ELEMENT& other_value)
{
  other_value.must_bound("Assignment of an unbound hexstring element to a "
    "hexstring.");
  unsigned char nibble_value = other_value.get_nibble();
  clean_up();
  init_struct(1);
  val_ptr->nibbles_ptr[0] = nibble_value;
  return *this;
}

boolean HEXSTRING::operator==(const HEXSTRING& other_value) const
{
  must_bound("Unbound left operand of hexstring comparison.");
  other_value.must_bound("Unbound right operand of hexstring comparison.");
  if (val_ptr->n_nibbles != other_value.val_ptr->n_nibbles) return FALSE;
  if (val_ptr->n_nibbles == 0) return TRUE;
  clear_unused_nibble();
  other_value.clear_unused_nibble();
  return !memcmp(val_ptr->nibbles_ptr, other_value.val_ptr->nibbles_ptr,
    (val_ptr->n_nibbles + 1) / 2);
}

boolean HEXSTRING::operator==(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Unbound left operand of hexstring comparison.");
  other_value.must_bound("Unbound right operand of hexstring element "
    "comparison.");
  if (val_ptr->n_nibbles != 1) return FALSE;
  return get_nibble(0) == other_value.get_nibble();
}

HEXSTRING HEXSTRING::operator+(const HEXSTRING& other_value) const
{
  must_bound("Unbound left operand of hexstring concatenation.");
  other_value.must_bound("Unbound right operand of hexstring concatenation.");

  int left_n_nibbles = val_ptr->n_nibbles;
  if (left_n_nibbles == 0) return other_value;

  int right_n_nibbles = other_value.val_ptr->n_nibbles;
  if (right_n_nibbles == 0) return *this;

  int n_nibbles = left_n_nibbles + right_n_nibbles;
  // the result
  HEXSTRING ret_val(n_nibbles);

  // the number of bytes used
  int left_n_bytes = (left_n_nibbles + 1) / 2;
  int right_n_bytes = (right_n_nibbles + 1) / 2;

  // pointers to the data areas
  const unsigned char *left_ptr = val_ptr->nibbles_ptr;
  const unsigned char *right_ptr = other_value.val_ptr->nibbles_ptr;
  unsigned char *dest_ptr = ret_val.val_ptr->nibbles_ptr;

  memcpy(dest_ptr, left_ptr, left_n_bytes);

  if (left_n_nibbles % 2) {
    dest_ptr[left_n_bytes - 1] &= 0x0F;
    int n_bytes = (n_nibbles + 1) / 2;
    for (int i = left_n_bytes; i < n_bytes; i++) {
      unsigned char right_byte = right_ptr[i - left_n_bytes];
      dest_ptr[i - 1] |= right_byte << 4;
      dest_ptr[i] = right_byte >> 4;
    }
    if (right_n_nibbles % 2) dest_ptr[n_bytes - 1] |= right_ptr[right_n_bytes
      - 1] << 4;
  }
  else {
    memcpy(dest_ptr + left_n_bytes, right_ptr, right_n_bytes);
    ret_val.clear_unused_nibble();
  }
  return ret_val;
}

HEXSTRING HEXSTRING::operator+(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Unbound left operand of hexstring concatenation.");
  other_value.must_bound("Unbound right operand of hexstring element "
    "concatenation.");
  int n_nibbles = val_ptr->n_nibbles;
  HEXSTRING ret_val(n_nibbles + 1);
  memcpy(ret_val.val_ptr->nibbles_ptr, val_ptr->nibbles_ptr, (n_nibbles + 1)
    / 2);
  ret_val.set_nibble(n_nibbles, other_value.get_nibble());
  return ret_val;
}

HEXSTRING HEXSTRING::operator~() const
{
  must_bound("Unbound hexstring operand of operator not4b.");

  int n_bytes = (val_ptr->n_nibbles + 1) / 2;
  if (n_bytes == 0) return *this;
  HEXSTRING ret_val(val_ptr->n_nibbles);
  for (int i = 0; i < n_bytes; i++) {
    ret_val.val_ptr->nibbles_ptr[i] = ~val_ptr->nibbles_ptr[i];
  }
  ret_val.clear_unused_nibble();
  return ret_val;
}

HEXSTRING HEXSTRING::operator&(const HEXSTRING& other_value) const
{
  must_bound("Left operand of operator and4b is an unbound hexstring value.");
  other_value.must_bound("Right operand of operator and4b is an unbound "
    "hexstring value.");
  int n_nibbles = val_ptr->n_nibbles;
  if (n_nibbles != other_value.val_ptr->n_nibbles) TTCN_error("The hexstring "
    "operands of operator and4b must have the same length.");
  if (n_nibbles == 0) return *this;
  HEXSTRING ret_val(n_nibbles);
  int n_bytes = (n_nibbles + 1) / 2;
  for (int i = 0; i < n_bytes; i++) {
    ret_val.val_ptr->nibbles_ptr[i] = val_ptr->nibbles_ptr[i]
      & other_value.val_ptr->nibbles_ptr[i];
  }
  ret_val.clear_unused_nibble();
  return ret_val;
}

HEXSTRING HEXSTRING::operator&(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Left operand of operator and4b is an unbound hexstring value.");
  other_value.must_bound("Right operand of operator and4b is an unbound "
    "hexstring element.");
  if (val_ptr->n_nibbles != 1) TTCN_error("The hexstring operands of operator "
    "and4b must have the same length.");
  unsigned char result = get_nibble(0) & other_value.get_nibble();
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING::operator|(const HEXSTRING& other_value) const
{
  must_bound("Left operand of operator or4b is an unbound hexstring value.");
  other_value.must_bound("Right operand of operator or4b is an unbound "
    "hexstring value.");
  int n_nibbles = val_ptr->n_nibbles;
  if (n_nibbles != other_value.val_ptr->n_nibbles) TTCN_error("The hexstring "
    "operands of operator or4b must have the same length.");
  if (n_nibbles == 0) return *this;
  HEXSTRING ret_val(n_nibbles);
  int n_bytes = (n_nibbles + 1) / 2;
  for (int i = 0; i < n_bytes; i++) {
    ret_val.val_ptr->nibbles_ptr[i] = val_ptr->nibbles_ptr[i]
      | other_value.val_ptr->nibbles_ptr[i];
  }
  ret_val.clear_unused_nibble();
  return ret_val;
}

HEXSTRING HEXSTRING::operator|(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Left operand of operator or4b is an unbound hexstring value.");
  other_value.must_bound("Right operand of operator or4b is an unbound "
    "hexstring element.");
  if (val_ptr->n_nibbles != 1) TTCN_error("The hexstring operands of operator "
    "or4b must have the same length.");
  unsigned char result = get_nibble(0) | other_value.get_nibble();
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING::operator^(const HEXSTRING& other_value) const
{
  must_bound("Left operand of operator xor4b is an unbound hexstring value.");
  other_value.must_bound("Right operand of operator xor4b is an unbound "
    "hexstring value.");
  int n_nibbles = val_ptr->n_nibbles;
  if (n_nibbles != other_value.val_ptr->n_nibbles) TTCN_error("The hexstring "
    "operands of operator xor4b must have the same length.");
  if (n_nibbles == 0) return *this;
  HEXSTRING ret_val(n_nibbles);
  int n_bytes = (n_nibbles + 1) / 2;
  for (int i = 0; i < n_bytes; i++) {
    ret_val.val_ptr->nibbles_ptr[i] = val_ptr->nibbles_ptr[i]
      ^ other_value.val_ptr->nibbles_ptr[i];
  }
  ret_val.clear_unused_nibble();
  return ret_val;
}

HEXSTRING HEXSTRING::operator^(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Left operand of operator xor4b is an unbound hexstring value.");
  other_value.must_bound("Right operand of operator xor4b is an unbound "
    "hexstring element.");
  if (val_ptr->n_nibbles != 1) TTCN_error("The hexstring operands of operator "
    "xor4b must have the same length.");
  unsigned char result = get_nibble(0) ^ other_value.get_nibble();
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING::operator<<(int shift_count) const
{
  must_bound("Unbound hexstring operand of shift left operator.");

  if (shift_count > 0) {
    int n_nibbles = val_ptr->n_nibbles;
    if (n_nibbles == 0) return *this;
    HEXSTRING ret_val(n_nibbles);
    int n_bytes = (n_nibbles + 1) / 2;
    clear_unused_nibble();
    if (shift_count > n_nibbles) shift_count = n_nibbles;
    int shift_bytes = shift_count / 2;
    if (shift_count % 2) {
      int byte_count = 0;
      for (; byte_count < n_bytes - shift_bytes - 1; byte_count++) {
        ret_val.val_ptr->nibbles_ptr[byte_count]
          = (val_ptr->nibbles_ptr[byte_count + shift_bytes] >> 4)
            | (val_ptr->nibbles_ptr[byte_count + shift_bytes + 1] << 4);
      }
      ret_val.val_ptr->nibbles_ptr[n_bytes - shift_bytes - 1]
        = val_ptr->nibbles_ptr[n_bytes - 1] >> 4;
    }
    else {
      memcpy(ret_val.val_ptr->nibbles_ptr, &val_ptr->nibbles_ptr[shift_count
        / 2], (n_nibbles - shift_count + 1) / 2);
    }
    memset(ret_val.val_ptr->nibbles_ptr + n_bytes - shift_bytes, 0, shift_bytes);
    return ret_val;
  }
  else if (shift_count == 0)
    return *this;
  else
    return *this >> (-shift_count);
}

HEXSTRING HEXSTRING::operator<<(const INTEGER& shift_count) const
{
  shift_count.must_bound("Unbound right operand of hexstring shift left "
    "operator.");
  return *this << (int) shift_count;
}

HEXSTRING HEXSTRING::operator>>(int shift_count) const
{
  must_bound("Unbound operand of hexstring shift right operator.");

  if (shift_count > 0) {
    int n_nibbles = val_ptr->n_nibbles;
    if (n_nibbles == 0) return *this;
    HEXSTRING ret_val(n_nibbles);
    clear_unused_nibble();
    if (shift_count > n_nibbles) shift_count = n_nibbles;
    int shift_bytes = shift_count / 2;
    memset(ret_val.val_ptr->nibbles_ptr, 0, shift_bytes);
    if (shift_count % 2) {
      ret_val.val_ptr->nibbles_ptr[shift_bytes] = val_ptr->nibbles_ptr[0] << 4;
426
      int n_bytes = (n_nibbles + 1) / 2;
Elemer Lelik's avatar
Elemer Lelik committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
      int byte_count = shift_bytes + 1;
      for (; byte_count < n_bytes; byte_count++) {
        ret_val.val_ptr->nibbles_ptr[byte_count]
          = (val_ptr->nibbles_ptr[byte_count - shift_bytes - 1] >> 4)
            | (val_ptr->nibbles_ptr[byte_count - shift_bytes] << 4);
      }
    }
    else {
      memcpy(&ret_val.val_ptr->nibbles_ptr[shift_bytes], val_ptr->nibbles_ptr,
        (n_nibbles - shift_count + 1) / 2);
    }
    ret_val.clear_unused_nibble();
    return ret_val;
  }
  else if (shift_count == 0)
    return *this;
  else
    return *this << (-shift_count);
}

HEXSTRING HEXSTRING::operator>>(const INTEGER& shift_count) const
{
  shift_count.must_bound("Unbound right operand of hexstring shift right "
    "operator.");
  return *this >> (int) shift_count;
}

HEXSTRING HEXSTRING::operator<<=(int rotate_count) const
{
  must_bound("Unbound hexstring operand of rotate left operator.");
  if (val_ptr->n_nibbles == 0) return *this;
  if (rotate_count >= 0) {
    rotate_count %= val_ptr->n_nibbles;
    if (rotate_count == 0) return *this;
    return ((*this) << rotate_count) | ((*this) >> (val_ptr->n_nibbles
      - rotate_count));
  }
  else
    return *this >>= (-rotate_count);
}

HEXSTRING HEXSTRING::operator<<=(const INTEGER& rotate_count) const
{
  rotate_count.must_bound("Unbound right operand of hexstring rotate left "
    "operator.");
  return *this <<= (int) rotate_count;
}

HEXSTRING HEXSTRING::operator>>=(int rotate_count) const
{
  must_bound("Unbound hexstring operand of rotate right operator.");
  if (val_ptr->n_nibbles == 0) return *this;
  if (rotate_count >= 0) {
    rotate_count %= val_ptr->n_nibbles;
    if (rotate_count == 0) return *this;
    return ((*this) >> rotate_count) | ((*this) << (val_ptr->n_nibbles
      - rotate_count));
  }
  else
    return *this <<= (-rotate_count);
}

HEXSTRING HEXSTRING::operator>>=(const INTEGER& rotate_count) const
{
  rotate_count.must_bound("Unbound right operand of hexstring rotate right "
    "operator.");
  return *this >>= (int) rotate_count;
}

HEXSTRING_ELEMENT HEXSTRING::operator[](int index_value)
{
  if (val_ptr == NULL && index_value == 0) {
    init_struct(1);
    clear_unused_nibble();
    return HEXSTRING_ELEMENT(FALSE, *this, 0);
  }
  else {
    must_bound("Accessing an element of an unbound hexstring value.");
    if (index_value < 0) TTCN_error("Accessing an hexstring element using "
      "a negative index (%d).", index_value);
    int n_nibbles = val_ptr->n_nibbles;
    if (index_value > n_nibbles) TTCN_error("Index overflow when accessing a "
      "hexstring element: The index is %d, but the string has only %d "
      "hexadecimal digits.", index_value, n_nibbles);
    if (index_value == n_nibbles) {
      if (val_ptr->ref_count == 1) {
        if (n_nibbles % 2 == 0) val_ptr
          = (hexstring_struct*) Realloc(val_ptr, MEMORY_SIZE(n_nibbles + 1));
        val_ptr->n_nibbles++;
      }
      else {
        hexstring_struct *old_ptr = val_ptr;
        old_ptr->ref_count--;
        init_struct(n_nibbles + 1);
        memcpy(val_ptr->nibbles_ptr, old_ptr->nibbles_ptr, (n_nibbles + 1) / 2);
      }
      return HEXSTRING_ELEMENT(FALSE, *this, index_value);
    }
    else
      return HEXSTRING_ELEMENT(TRUE, *this, index_value);
  }
}

HEXSTRING_ELEMENT HEXSTRING::operator[](const INTEGER& index_value)
{
  index_value.must_bound("Indexing a hexstring value with an unbound integer "
    "value.");
  return (*this)[(int) index_value];
}

const HEXSTRING_ELEMENT HEXSTRING::operator[](int index_value) const
{
  must_bound("Accessing an element of an unbound hexstring value.");
  if (index_value < 0) TTCN_error("Accessing an hexstring element using a "
    "negative index (%d).", index_value);
  if (index_value >= val_ptr->n_nibbles) TTCN_error("Index overflow when "
    "accessing a hexstring element: The index is %d, but the string has only "
    "%d hexadecimal digits.", index_value, val_ptr->n_nibbles);
  return HEXSTRING_ELEMENT(TRUE, const_cast<HEXSTRING&> (*this), index_value);
}

const HEXSTRING_ELEMENT HEXSTRING::operator[](const INTEGER& index_value) const
{
  index_value.must_bound("Indexing a hexstring value with an unbound integer "
    "value.");
  return (*this)[(int) index_value];
}

int HEXSTRING::lengthof() const
{
  must_bound("Getting the length of an unbound hexstring value.");
  return val_ptr->n_nibbles;
}

HEXSTRING::operator const unsigned char*() const
{
  must_bound("Casting an unbound hexstring value to const unsigned char*.");
  return val_ptr->nibbles_ptr;
}

void HEXSTRING::log() const
{
  if (val_ptr != NULL) {
    TTCN_Logger::log_char('\'');
    for (int i = 0; i < val_ptr->n_nibbles; i++)
      TTCN_Logger::log_hex(get_nibble(i));
    TTCN_Logger::log_event_str("'H");
  }
  else {
    TTCN_Logger::log_event_unbound();
  }
}

void HEXSTRING::encode_text(Text_Buf& text_buf) const
{
  must_bound("Text encoder: Encoding an unbound hexstring value");
  int n_nibbles = val_ptr->n_nibbles;
  text_buf.push_int(n_nibbles);
  if (n_nibbles > 0) text_buf.push_raw((n_nibbles + 1) / 2,
    val_ptr->nibbles_ptr);
}

void HEXSTRING::decode_text(Text_Buf& text_buf)
{
  int n_nibbles = text_buf.pull_int().get_val();
  if (n_nibbles < 0) TTCN_error(
    "Text decoder: Invalid length was received for a hexstring.");
  clean_up();
  init_struct(n_nibbles);
  if (n_nibbles > 0) {
    text_buf.pull_raw((n_nibbles + 1) / 2, val_ptr->nibbles_ptr);
    clear_unused_nibble();
  }
}

void HEXSTRING::set_param(Module_Param& param) {
  param.basic_check(Module_Param::BC_VALUE|Module_Param::BC_LIST, "hexstring value");
Elemer Lelik's avatar
Elemer Lelik committed
604
  Module_Param_Ptr mp = &param;
605
#ifdef TITAN_RUNTIME_2
Elemer Lelik's avatar
Elemer Lelik committed
606
607
608
  if (param.get_type() == Module_Param::MP_Reference) {
    mp = param.get_referenced_param();
  }
609
#endif
Elemer Lelik's avatar
Elemer Lelik committed
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
  switch (mp->get_type()) {
  case Module_Param::MP_Hexstring:
    switch (param.get_operation_type()) {
    case Module_Param::OT_ASSIGN: {
      clean_up();
      int n_nibbles = mp->get_string_size();
      init_struct(n_nibbles);
      memcpy(val_ptr->nibbles_ptr, mp->get_string_data(), (n_nibbles + 1) / 2);
      clear_unused_nibble();
    } break;
    case Module_Param::OT_CONCAT:
      if (is_bound()) {
        *this = *this + HEXSTRING(mp->get_string_size(), (unsigned char*)mp->get_string_data());
      } else {
        *this = HEXSTRING(mp->get_string_size(), (unsigned char*)mp->get_string_data());
      }
      break;
    default:
      TTCN_error("Internal error: HEXSTRING::set_param()");
    }
    break;
  case Module_Param::MP_Expression:
    if (mp->get_expr_type() == Module_Param::EXPR_CONCATENATE) {
      HEXSTRING operand1, operand2;
      operand1.set_param(*mp->get_operand1());
      operand2.set_param(*mp->get_operand2());
      if (param.get_operation_type() == Module_Param::OT_CONCAT) {
        *this = *this + operand1 + operand2;
      }
      else {
        *this = operand1 + operand2;
      }
    }
    else {
      param.expr_type_error("a hexstring");
Elemer Lelik's avatar
Elemer Lelik committed
645
646
647
    }
    break;
  default:
Elemer Lelik's avatar
Elemer Lelik committed
648
649
650
651
652
    param.type_error("hexstring value");
    break;
  }
}

653
#ifdef TITAN_RUNTIME_2
Elemer Lelik's avatar
Elemer Lelik committed
654
655
656
657
658
659
660
661
662
Module_Param* HEXSTRING::get_param(Module_Param_Name& /* param_name */) const
{
  if (!is_bound()) {
    return new Module_Param_Unbound();
  }
  int n_bytes = (val_ptr->n_nibbles + 1) / 2;
  unsigned char* val_cpy = (unsigned char *)Malloc(n_bytes);
  memcpy(val_cpy, val_ptr->nibbles_ptr, n_bytes);
  return new Module_Param_Hexstring(val_ptr->n_nibbles, val_cpy);
Elemer Lelik's avatar
Elemer Lelik committed
663
}
664
#endif
Elemer Lelik's avatar
Elemer Lelik committed
665
666

void HEXSTRING::encode(const TTCN_Typedescriptor_t& p_td, TTCN_Buffer& p_buf,
667
  int p_coding, ...) const
Elemer Lelik's avatar
Elemer Lelik committed
668
669
670
671
672
673
674
675
676
677
678
{
  va_list pvar;
  va_start(pvar, p_coding);
  switch (p_coding) {
  case TTCN_EncDec::CT_RAW: {
    TTCN_EncDec_ErrorContext ec("While RAW-encoding type '%s': ", p_td.name);
    if (!p_td.raw) TTCN_EncDec_ErrorContext::error_internal(
      "No RAW descriptor available for type '%s'.", p_td.name);
    RAW_enc_tr_pos rp;
    rp.level = 0;
    rp.pos = NULL;
679
    RAW_enc_tree root(TRUE, NULL, &rp, 1, p_td.raw);
Elemer Lelik's avatar
Elemer Lelik committed
680
681
682
683
684
685
    RAW_encode(p_td, root);
    root.put_to_buf(p_buf);
    break;}
  case TTCN_EncDec::CT_XER: {
    TTCN_EncDec_ErrorContext ec("While XER-encoding type '%s': ", p_td.name);
    unsigned XER_coding=va_arg(pvar, unsigned);
686
    XER_encode(*p_td.xer, p_buf, XER_coding, 0, 0, 0);
Elemer Lelik's avatar
Elemer Lelik committed
687
688
689
690
691
692
693
    break;}
  case TTCN_EncDec::CT_JSON: {
    TTCN_EncDec_ErrorContext ec("While JSON-encoding type '%s': ", p_td.name);
    if(!p_td.json)
      TTCN_EncDec_ErrorContext::error_internal
        ("No JSON descriptor available for type '%s'.", p_td.name);
    JSON_Tokenizer tok(va_arg(pvar, int) != 0);
694
    JSON_encode(p_td, tok, FALSE);
Elemer Lelik's avatar
Elemer Lelik committed
695
696
697
698
699
700
701
702
703
    p_buf.put_s(tok.get_buffer_length(), (const unsigned char*)tok.get_buffer());
    break;}
  default:
    TTCN_error("Unknown coding method requested to encode type '%s'", p_td.name);
  }
  va_end(pvar);
}

void HEXSTRING::decode(const TTCN_Typedescriptor_t& p_td, TTCN_Buffer& p_buf,
704
  int p_coding, ...)
Elemer Lelik's avatar
Elemer Lelik committed
705
706
{
  va_list pvar;
707
  va_start(pvar, p_coding);
Elemer Lelik's avatar
Elemer Lelik committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
  switch (p_coding) {
  case TTCN_EncDec::CT_RAW: {
    TTCN_EncDec_ErrorContext ec("While RAW-decoding type '%s': ", p_td.name);
    if (!p_td.raw) TTCN_EncDec_ErrorContext::error_internal(
      "No RAW descriptor available for type '%s'.", p_td.name);
    raw_order_t order;
    switch (p_td.raw->top_bit_order) {
    case TOP_BIT_LEFT:
      order = ORDER_LSB;
      break;
    case TOP_BIT_RIGHT:
    default:
      order = ORDER_MSB;
    }
    if (RAW_decode(p_td, p_buf, p_buf.get_len() * 8, order) < 0) ec.error(
      TTCN_EncDec::ET_INCOMPL_MSG,
      "Can not decode type '%s', because invalid or incomplete"
        " message was received", p_td.name);
    break;}
  case TTCN_EncDec::CT_XER: {
Elemer Lelik's avatar
Elemer Lelik committed
728
    TTCN_EncDec_ErrorContext ec("While XER-decoding type '%s': ", p_td.name);
Elemer Lelik's avatar
Elemer Lelik committed
729
730
731
732
733
734
735
736
    unsigned XER_coding=va_arg(pvar, unsigned);
    XmlReaderWrap reader(p_buf);
    int success = reader.Read();
    for (; success==1; success=reader.Read()) {
      int type = reader.NodeType();
      if (type==XML_READER_TYPE_ELEMENT)
        break;
    }
Elemer Lelik's avatar
Elemer Lelik committed
737
    XER_decode(*p_td.xer, reader, XER_coding, XER_NONE, 0);
Elemer Lelik's avatar
Elemer Lelik committed
738
739
740
741
    size_t bytes = reader.ByteConsumed();
    p_buf.set_pos(bytes);
    break;}
  case TTCN_EncDec::CT_JSON: {
Elemer Lelik's avatar
Elemer Lelik committed
742
    TTCN_EncDec_ErrorContext ec("While JSON-decoding type '%s': ", p_td.name);
Elemer Lelik's avatar
Elemer Lelik committed
743
744
745
746
    if(!p_td.json)
      TTCN_EncDec_ErrorContext::error_internal
        ("No JSON descriptor available for type '%s'.", p_td.name);
    JSON_Tokenizer tok((const char*)p_buf.get_data(), p_buf.get_len());
747
    if(JSON_decode(p_td, tok, FALSE, FALSE)<0)
Elemer Lelik's avatar
Elemer Lelik committed
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
      ec.error(TTCN_EncDec::ET_INCOMPL_MSG,
               "Can not decode type '%s', because invalid or incomplete"
               " message was received"
               , p_td.name);
    p_buf.set_pos(tok.get_buf_pos());
    break;}
  default:
    TTCN_error("Unknown coding method requested to decode type '%s'", p_td.name);
  }
  va_end(pvar);
}

int HEXSTRING::RAW_encode(const TTCN_Typedescriptor_t& p_td,
  RAW_enc_tree& myleaf) const
{
  //  unsigned char *bc;
  if (!is_bound()) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_UNBOUND,
      "Encoding an unbound value.");
  }
  int nbits = val_ptr->n_nibbles * 4;
  int align_length = p_td.raw->fieldlength ? p_td.raw->fieldlength - nbits : 0;
  if ((nbits + align_length) < val_ptr->n_nibbles * 4) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_LEN_ERR,
      "There is no sufficient bits to encode '%s': ", p_td.name);
    nbits = p_td.raw->fieldlength;
    align_length = 0;
  }

  if (myleaf.must_free) Free(myleaf.body.leaf.data_ptr);

779
780
  myleaf.must_free = FALSE;
  myleaf.data_ptr_used = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
781
782
783
784
785
786
  myleaf.body.leaf.data_ptr = val_ptr->nibbles_ptr;

  if (p_td.raw->endianness == ORDER_MSB)
    myleaf.align = -align_length;
  else
    myleaf.align = align_length;
787
  myleaf.coding_par.csn1lh = p_td.raw->csn1lh;
Elemer Lelik's avatar
Elemer Lelik committed
788
789
790
791
792
  return myleaf.length = nbits + align_length;
}

int HEXSTRING::RAW_decode(const TTCN_Typedescriptor_t& p_td, TTCN_Buffer& buff,
  int limit, raw_order_t top_bit_ord, boolean no_err, int /*sel_field*/,
793
  boolean /*first_call*/, const RAW_Force_Omit* /*force_omit*/)
Elemer Lelik's avatar
Elemer Lelik committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
{
  int prepaddlength = buff.increase_pos_padd(p_td.raw->prepadding);
  limit -= prepaddlength;
  int decode_length = p_td.raw->fieldlength == 0
    ? (limit / 4) * 4 : p_td.raw->fieldlength;
  if ( p_td.raw->fieldlength > limit
    || p_td.raw->fieldlength > (int) buff.unread_len_bit()) {
    if (no_err) return -TTCN_EncDec::ET_LEN_ERR;
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_LEN_ERR,
      "There is not enough bits in the buffer to decode type %s.", p_td.name);
    decode_length = ((limit > (int) buff.unread_len_bit()
      ? (int)buff.unread_len_bit() : limit) / 4) * 4;
  }
  RAW_coding_par cp;
Kristof Szabados's avatar
Kristof Szabados committed
808
  boolean orders = p_td.raw->bitorderinoctet == ORDER_MSB;
Elemer Lelik's avatar
Elemer Lelik committed
809
810
  if (p_td.raw->bitorderinfield == ORDER_MSB) orders = !orders;
  cp.bitorder = orders ? ORDER_MSB : ORDER_LSB;
Kristof Szabados's avatar
Kristof Szabados committed
811
  orders = p_td.raw->byteorder == ORDER_MSB;
Elemer Lelik's avatar
Elemer Lelik committed
812
813
814
815
  if (p_td.raw->bitorderinfield == ORDER_MSB) orders = !orders;
  cp.byteorder = orders ? ORDER_MSB : ORDER_LSB;
  cp.fieldorder = p_td.raw->fieldorder;
  cp.hexorder = p_td.raw->hexorder;
816
  cp.csn1lh = p_td.raw->csn1lh;
Elemer Lelik's avatar
Elemer Lelik committed
817
818
819
820
  clean_up();
  init_struct(decode_length / 4);
  buff.get_b((size_t) decode_length, val_ptr->nibbles_ptr, cp, top_bit_ord);

821
822
  if (p_td.raw->length_restrition != -1 &&
      decode_length > p_td.raw->length_restrition) {
Elemer Lelik's avatar
Elemer Lelik committed
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
    val_ptr->n_nibbles = p_td.raw->length_restrition;
    if (p_td.raw->endianness == ORDER_MSB) {
      if ((decode_length - val_ptr->n_nibbles * 4) % 8) {
        int bound = (decode_length - val_ptr->n_nibbles * 4) % 8;
        int maxindex = (decode_length - 1) / 8;
        for (int a = 0, b = (decode_length - val_ptr->n_nibbles * 4 - 1) / 8; a
          < (val_ptr->n_nibbles * 4 + 7) / 8; a++, b++) {
          val_ptr->nibbles_ptr[a] = val_ptr->nibbles_ptr[b] >> bound;
          if (b < maxindex)
            val_ptr->nibbles_ptr[a] = val_ptr->nibbles_ptr[b + 1] << (8 - bound);
        }
      }
      else memmove(val_ptr->nibbles_ptr,
        val_ptr->nibbles_ptr + (decode_length - val_ptr->n_nibbles * 4) / 8,
        val_ptr->n_nibbles * 8 * sizeof(unsigned char));
    }
  }

  /*  for(int a=0; a<decode_length/8; a++)
   val_ptr->nibbles_ptr[a]= ((val_ptr->nibbles_ptr[a]<<4)&0xf0) |
   ((val_ptr->nibbles_ptr[a]>>4)&0x0f);*/
  decode_length += buff.increase_pos_padd(p_td.raw->padding);
  clear_unused_nibble();
  return decode_length + prepaddlength;
}

// From Charstring.cc
extern char  base64_decoder_table[256];
extern const char cb64[];

int HEXSTRING::XER_encode(const XERdescriptor_t& p_td,
854
  TTCN_Buffer& p_buf, unsigned int flavor, unsigned int /*flavor2*/, int indent, embed_values_enc_struct_t*) const
Elemer Lelik's avatar
Elemer Lelik committed
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
{
  if(!is_bound()) {
    TTCN_EncDec_ErrorContext::error
      (TTCN_EncDec::ET_UNBOUND, "Encoding an unbound hexstring value.");
  }
  int exer  = is_exer(flavor |= SIMPLE_TYPE);
  // SIMPLE_TYPE has no influence on is_exer, we set it for later
  int encoded_length=(int)p_buf.get_len();
  int empty_element = val_ptr==NULL || val_ptr->n_nibbles == 0;

  flavor &= ~XER_RECOF; // octetstring doesn't care
  begin_xml(p_td, p_buf, flavor, indent, empty_element);

  if (exer && (p_td.xer_bits & BASE_64)) {
    // bit more work
    size_t clear_len = (val_ptr->n_nibbles + 1) / 2; // lengthof is in nibbles
    const unsigned char * in = val_ptr->nibbles_ptr;

    /* Encode (up to) 6 nibbles of cleartext into 4 bytes of base64.
     * This is different from Octetstring.cc because hexstring's
     * big-endian data storage. */
    for (size_t i = 0; i < clear_len; i += 3) {
      unsigned char first  = in[i],
        second = ((i+1 < clear_len) ? in[i+1] :0),
        third  = ((i+2 < clear_len) ? in[i+2] :0);

      p_buf.put_c(cb64[(first & 0x0F) << 2 | first >> 6]);
      p_buf.put_c(cb64[(first & 0x30)      | (second & 0x0F)]);
      p_buf.put_c(i+1 >= clear_len ? '='
        : cb64[(second & 0xF0) >> 2 | (third & 0x0C) >> 2]);
      p_buf.put_c( i+2 >= clear_len ? '='
        : cb64[(third  & 0x03) << 4 | (third & 0xF0) >> 4]);
    } // next i
  }
  else {
    CHARSTRING val = hex2str(*this);
    p_buf.put_string(val);
  }

  end_xml(p_td, p_buf, flavor, indent, empty_element);

  return (int)p_buf.get_len() - encoded_length;

}

900
unsigned int xlate_hs(xmlChar in[4], int phase, unsigned char*dest) {
Elemer Lelik's avatar
Elemer Lelik committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
  static unsigned char nbytes[4] = { 3,1,1,2 };
  unsigned char out[4];

  out[0] = in[0] >> 2 | (in[0] & 3) << 6 | (in[1] & 0x30);
  out[1] = (in[1] & 0x0F) | (in[2] & 0x3C) << 2;
  out[2] = (in[3] & 0x0F) << 4 | (in[3] & 0x30) >> 4 | (in[2] & 3) << 2;
  memcpy(dest, out, nbytes[phase]);
  return nbytes[phase];
}


/* Here's how the bits get transferred to and from Base64:

Titan stores the hex digits in "little endian order", the first (index 0)
goes into the lower nibble, the second goes into the high nibble
of the first byte. So, For the hexstring value 'DECAFBAD'H,
Titan stores the following bytes: ED AC BF DA

Because of this, the bit shifting is different. The first three bytes

3x8 bits: eeeedddd aaaacccc bbbbffff

4x6 bits: ddddee eecccc aaaaff ffbbbb

*/

int HEXSTRING::XER_decode(const XERdescriptor_t& p_td, XmlReaderWrap& reader,
Elemer Lelik's avatar
Elemer Lelik committed
928
  unsigned int flavor, unsigned int /*flavor2*/, embed_values_dec_struct_t*)
Elemer Lelik's avatar
Elemer Lelik committed
929
{
930
  boolean exer  = is_exer(flavor);
Elemer Lelik's avatar
Elemer Lelik committed
931
932
933
934
935
936
937
938
939
940
941
  int success = reader.Ok(), depth = -1, type;
  boolean own_tag = !is_exerlist(flavor) && !(exer && (p_td.xer_bits & UNTAGGED));

  if (exer && (p_td.xer_bits & XER_ATTRIBUTE)) {
    const char * name = verify_name(reader, p_td, exer);
    (void)name;
  }
  else
   if (own_tag) for (; success == 1; success = reader.Read()) {
    type = reader.NodeType();
    if (XML_READER_TYPE_ELEMENT == type) {
942
943
944
945
946
      // If our parent is optional and there is an unexpected tag then return and
      // we stay unbound.
      if ((flavor & XER_OPTIONAL) && !check_name((const char*)reader.LocalName(), p_td, exer)) {
        return -1;
      }
Elemer Lelik's avatar
Elemer Lelik committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
      verify_name(reader, p_td, exer);
      depth = reader.Depth();
      if (reader.IsEmptyElement()) {
        if (exer && p_td.dfeValue != 0) {
          *this = *static_cast<const HEXSTRING*> (p_td.dfeValue);
        }
        else init_struct(0);
        reader.Read();
        goto finished;
      }
    }
    else if (XML_READER_TYPE_TEXT == type && depth != -1) break;
    else if (XML_READER_TYPE_END_ELEMENT ==  type) {
      // End tag without intervening #text == empty content
      verify_end(reader, p_td, depth, exer);
      if (exer && p_td.dfeValue != 0) {
        *this = *static_cast<const HEXSTRING*>(p_td.dfeValue);
      }
      else init_struct(0);
      reader.Read();
      goto finished;
    }
  }

  type = reader.NodeType();
  if (success == 1 && (XML_READER_TYPE_TEXT == type || XML_READER_TYPE_ATTRIBUTE == type)) {
973
    const char * value = (const char *)reader.Value();
Elemer Lelik's avatar
Elemer Lelik committed
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
    size_t len = value ? strlen(value) : 0;

    if (exer && (p_td.xer_bits & BASE_64)) {
      xmlChar in[4];

      int phase = 0;
      init_struct(len * 3 / 2); // 4 bytes decoded into 3 octets (6 nibbles)
      unsigned char * dest = val_ptr->nibbles_ptr;

      for (size_t o=0; o<len; ++o) {
        xmlChar c = value[o];
        if(c == '=') { // padding starts
          dest += xlate_hs(in, phase, dest);
          break;
        }

        int val = base64_decoder_table[c];
        if(val >= 0)    {
          in[phase] = val;
          phase = (phase + 1) % 4;
          if(phase == 0) {
            dest += xlate_hs(in,phase, dest);
            in[0]=in[1]=in[2]=in[3]=0;
          }
        }
        else if (exer && (flavor & EXIT_ON_ERROR)) {
          clean_up();
          return -1;
        } else {
          TTCN_EncDec_ErrorContext::warning(
            /* if this was an error... TTCN_EncDec::ET_INVAL_MSG,*/
            "Invalid character for Base64 '%02X'", c);
        }
      } // while
      // adjust
      val_ptr->n_nibbles = (dest - val_ptr->nibbles_ptr) * 2;

    }
    else { // not base64
      init_struct(len);

      for (size_t i = 0; i < len; ++i) {
        unsigned char nibble = char_to_hexdigit(value[i]);
        if (nibble > 0x0F) {
          if (exer && (flavor & EXIT_ON_ERROR)) {
            clean_up();
            return -1;
          } else {
            TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_INVAL_MSG,
              "The hexstring value may contain hexadecimal digits only. "
              "Character \"%c\" was found.", value[i]);
            nibble=0;
          }
        }
        //val_ptr->nibbles_ptr[i] = nibble;
        set_nibble(i, nibble);
      } // next
    } // if base64
  } // if success

  if (exer && (p_td.xer_bits & XER_ATTRIBUTE)) {
    // Let the caller do reader.AdvanceAttribute();
  }
  else
  if (own_tag) for (success = reader.Read(); success == 1; success = reader.Read()) {
    type = reader.NodeType();
    if (XML_READER_TYPE_END_ELEMENT == type) {
      verify_end(reader, p_td, depth, exer);
      if (val_ptr == 0 && p_td.dfeValue != 0) {
        // The end tag must have followed the start tag
        *this = *static_cast<const HEXSTRING*>(p_td.dfeValue);
      }
      reader.Read(); // one last time
      break;
    }
  }
finished:
  return 1; // decode successful
}

1054
int HEXSTRING::JSON_encode(const TTCN_Typedescriptor_t&, JSON_Tokenizer& p_tok, boolean) const
Elemer Lelik's avatar
Elemer Lelik committed
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
{
  if (!is_bound()) {
    TTCN_EncDec_ErrorContext::error(TTCN_EncDec::ET_UNBOUND,
      "Encoding an unbound hexstring value.");
    return -1;
  }
  
  char* tmp_str = (char*)Malloc(val_ptr->n_nibbles + 3);
  tmp_str[0] = '\"';
  tmp_str[val_ptr->n_nibbles + 1] = '\"';
  for(int i = 0; i < val_ptr->n_nibbles; ++i) {
    if (i % 2) {
      tmp_str[i + 1] = hexdigit_to_char(val_ptr->nibbles_ptr[i / 2] >> 4);
    } else {
      tmp_str[i + 1] = hexdigit_to_char(val_ptr->nibbles_ptr[i / 2] & 0x0F);
    }
  }
  tmp_str[val_ptr->n_nibbles + 2] = 0;
  int enc_len = p_tok.put_next_token(JSON_TOKEN_STRING, tmp_str);
  Free(tmp_str);
  return enc_len;
}

1078
int HEXSTRING::JSON_decode(const TTCN_Typedescriptor_t& p_td, JSON_Tokenizer& p_tok, boolean p_silent, boolean, int)
Elemer Lelik's avatar
Elemer Lelik committed
1079
1080
1081
1082
{
  json_token_t token = JSON_TOKEN_NONE;
  char* value = 0;
  size_t value_len = 0;
1083
  boolean error = FALSE;
1084
  size_t dec_len = 0;
Elemer Lelik's avatar
Elemer Lelik committed
1085
1086
1087
  boolean use_default = p_td.json->default_value && 0 == p_tok.get_buffer_length();
  if (use_default) {
    // No JSON data in the buffer -> use default value
1088
    value = const_cast<char*>(p_td.json->default_value);
Elemer Lelik's avatar
Elemer Lelik committed
1089
1090
1091
1092
1093
1094
1095
1096
1097
    value_len = strlen(value);
  } else {
    dec_len = p_tok.get_next_token(&token, &value, &value_len);
  }
  if (JSON_TOKEN_ERROR == token) {
    JSON_ERROR(TTCN_EncDec::ET_INVAL_MSG, JSON_DEC_BAD_TOKEN_ERROR, "");
    return JSON_ERROR_FATAL;
  }
  else if (JSON_TOKEN_STRING == token || use_default) {
1098
    if (use_default || (value_len >= 2 && value[0] == '\"' && value[value_len - 1] == '\"')) {
Elemer Lelik's avatar
Elemer Lelik committed
1099
1100
1101
1102
1103
      if (!use_default) {
        // The default value doesn't have quotes around it
        value_len -= 2;
        ++value;
      }
1104
1105
1106
      // White spaces are ignored, so the resulting hexstring might be shorter
      // than the extracted JSON string
      int nibbles = value_len;
Elemer Lelik's avatar
Elemer Lelik committed
1107
      for (size_t i = 0; i < value_len; ++i) {
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
        if (value[i] == ' ') {
          --nibbles;
        }
        else if (!isxdigit(value[i])) {
          if (value[i] == '\\' && i + 1 < value_len &&
              (value[i + 1] == 'n' || value[i + 1] == 'r' || value[i + 1] == 't')) {
            // Escaped white space character
            ++i;
            nibbles -= 2;
          }
          else {
            error = TRUE;
            break;
          }
        }
      }
      if (!error) {
1125
        clean_up();
1126
1127
1128
1129
1130
1131
1132
1133
1134
        init_struct(nibbles);
        int nibble_index = 0;
        for (size_t i = 0; i < value_len; ++i) {
          if (!isxdigit(value[i])) {
            continue;
          }
          set_nibble(nibble_index, char_to_hexdigit(value[i]));
          ++nibble_index;
        }
1135
        clear_unused_nibble();
Elemer Lelik's avatar
Elemer Lelik committed
1136
1137
      }
    } else {
1138
      error = TRUE;
Elemer Lelik's avatar
Elemer Lelik committed
1139
1140
1141
1142
1143
1144
1145
1146
1147
    }
  } else {
    return JSON_ERROR_INVALID_TOKEN;
  }
  
  if (error) {
    JSON_ERROR(TTCN_EncDec::ET_INVAL_MSG, JSON_DEC_FORMAT_ERROR, "string", "hexstring");
    return JSON_ERROR_FATAL;    
  }
1148
  return (int)dec_len;
Elemer Lelik's avatar
Elemer Lelik committed
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
}


//---------------------- hexstring element class ----------------------

HEXSTRING_ELEMENT::HEXSTRING_ELEMENT(boolean par_bound_flag,
  HEXSTRING& par_str_val, int par_nibble_pos) :
  bound_flag(par_bound_flag), str_val(par_str_val), nibble_pos(par_nibble_pos)
{
}

HEXSTRING_ELEMENT& HEXSTRING_ELEMENT::operator=(
  const HEXSTRING_ELEMENT& other_value)
{
  other_value.must_bound("Assignment of an unbound hexstring element.");
  bound_flag = TRUE;
  str_val.copy_value();
  str_val.set_nibble(nibble_pos, other_value.str_val.get_nibble(
    other_value.nibble_pos));
  return *this;
}

HEXSTRING_ELEMENT& HEXSTRING_ELEMENT::operator=(const HEXSTRING& other_value)
{
  other_value.must_bound("Assignment of unbound hexstring value.");
  if (other_value.lengthof() != 1) TTCN_error(
    "Assignment of a hexstring value "
      "with length other than 1 to a hexstring element.");
  bound_flag = TRUE;
  str_val.copy_value();
  str_val.set_nibble(nibble_pos, other_value.get_nibble(0));
  return *this;
}

boolean HEXSTRING_ELEMENT::operator==(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Unbound left operand of hexstring element comparison.");
  other_value.must_bound("Unbound right operand of hexstring comparison.");
  return str_val.get_nibble(nibble_pos) == other_value.str_val.get_nibble(
    other_value.nibble_pos);
}

boolean HEXSTRING_ELEMENT::operator==(const HEXSTRING& other_value) const
{
  must_bound("Unbound left operand of hexstring element comparison.");
  other_value.must_bound("Unbound right operand of hexstring element "
    "comparison.");
  if (other_value.val_ptr->n_nibbles != 1) return FALSE;
  return str_val.get_nibble(nibble_pos) == other_value.get_nibble(0);
}

HEXSTRING HEXSTRING_ELEMENT::operator+(const HEXSTRING& other_value) const
{
  must_bound("Unbound left operand of hexstring element concatenation.");
  other_value.must_bound("Unbound right operand of hexstring concatenation.");
  int n_nibbles = other_value.val_ptr->n_nibbles;
  HEXSTRING ret_val(n_nibbles + 1);
  const unsigned char *src_ptr = other_value.val_ptr->nibbles_ptr;
  unsigned char *dest_ptr = ret_val.val_ptr->nibbles_ptr;
  dest_ptr[0] = str_val.get_nibble(nibble_pos);
  // bytes in the result minus 1
  int n_complete_bytes = n_nibbles / 2;
  for (int i = 0; i < n_complete_bytes; i++) {
    unsigned char right_octet = src_ptr[i];
    dest_ptr[i] |= right_octet << 4;
    dest_ptr[i + 1] = right_octet >> 4;
  }
  if (n_nibbles % 2) dest_ptr[n_complete_bytes] |= src_ptr[n_complete_bytes]
    << 4;
  return ret_val;
}

HEXSTRING HEXSTRING_ELEMENT::operator+(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Unbound left operand of hexstring element concatenation.");
  other_value.must_bound("Unbound right operand of hexstring element "
    "concatenation.");
  unsigned char result = str_val.get_nibble(nibble_pos)
    | (other_value.str_val.get_nibble(other_value.nibble_pos) << 4);
  return HEXSTRING(2, &result);
}

HEXSTRING HEXSTRING_ELEMENT::operator~() const
{
  must_bound("Unbound hexstring element operand of operator not4b.");
  unsigned char result = ~str_val.get_nibble(nibble_pos) & 0x0F;
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING_ELEMENT::operator&(const HEXSTRING& other_value) const
{
  must_bound("Left operand of operator and4b is an unbound hexstring element.");
  other_value.must_bound("Right operand of operator and4b is an unbound "
    "hexstring value.");
  if (other_value.val_ptr->n_nibbles != 1) TTCN_error("The hexstring operands "
    "of operator and4b must have the same length.");
  unsigned char result = str_val.get_nibble(nibble_pos)
    & other_value.get_nibble(0);
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING_ELEMENT::operator&(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Left operand of operator and4b is an unbound hexstring element.");
  other_value.must_bound("Right operand of operator and4b is an unbound "
    "hexstring element.");
  unsigned char result = str_val.get_nibble(nibble_pos)
    & other_value.str_val.get_nibble(other_value.nibble_pos);
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING_ELEMENT::operator|(const HEXSTRING& other_value) const
{
  must_bound("Left operand of operator or4b is an unbound hexstring element.");
  other_value.must_bound("Right operand of operator or4b is an unbound "
    "hexstring value.");
  if (other_value.val_ptr->n_nibbles != 1) TTCN_error("The hexstring operands "
    "of operator or4b must have the same length.");
  unsigned char result = str_val.get_nibble(nibble_pos)
    | other_value.get_nibble(0);
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING_ELEMENT::operator|(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Left operand of operator or4b is an unbound hexstring element.");
  other_value.must_bound("Right operand of operator or4b is an unbound "
    "hexstring element.");
  unsigned char result = str_val.get_nibble(nibble_pos)
    | other_value.str_val.get_nibble(other_value.nibble_pos);
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING_ELEMENT::operator^(const HEXSTRING& other_value) const
{
  must_bound("Left operand of operator xor4b is an unbound hexstring element.");
  other_value.must_bound("Right operand of operator xor4b is an unbound "
    "hexstring value.");
  if (other_value.val_ptr->n_nibbles != 1) TTCN_error("The hexstring operands "
    "of operator xor4b must have the same length.");
  unsigned char result = str_val.get_nibble(nibble_pos)
    ^ other_value.get_nibble(0);
  return HEXSTRING(1, &result);
}

HEXSTRING HEXSTRING_ELEMENT::operator^(const HEXSTRING_ELEMENT& other_value) const
{
  must_bound("Left operand of operator xor4b is an unbound hexstring element.");
  other_value.must_bound("Right operand of operator xor4b is an unbound "
    "hexstring element.");
  unsigned char result = str_val.get_nibble(nibble_pos)
    ^ other_value.str_val.get_nibble(other_value.nibble_pos);
  return HEXSTRING(1, &result);
}

unsigned char HEXSTRING_ELEMENT::get_nibble() const
{
  return str_val.get_nibble(nibble_pos);
}

void HEXSTRING_ELEMENT::log() const
{
  if (bound_flag) {
    TTCN_Logger::log_char('\'');
    TTCN_Logger::log_hex(str_val.get_nibble(nibble_pos));
    TTCN_Logger::log_event_str("'H");
  }
  else {
    TTCN_Logger::log_event_unbound();
  }
}

//---------------------- hexstring template class ----------------------

void HEXSTRING_template::clean_up()
{
  switch (template_selection) {
  case VALUE_LIST:
  case COMPLEMENTED_LIST:
    delete[] value_list.list_value;
    break;
  case STRING_PATTERN:
    if (pattern_value->ref_count > 1)
      pattern_value->ref_count--;
    else if (pattern_value->ref_count == 1)
      Free(pattern_value);
    else
      TTCN_error("Internal error: Invalid reference counter in a hexstring "
        "pattern.");
    break;
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
  case DECODE_MATCH:
    if (dec_match->ref_count > 1) {
      dec_match->ref_count--;
    }
    else if (dec_match->ref_count == 1) {
      delete dec_match->instance;
      delete dec_match;
    }
    else {
      TTCN_error("Internal error: Invalid reference counter in a "
        "decoded content match.");
    }
    break;
Elemer Lelik's avatar
Elemer Lelik committed
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
  default:
    break;
  }
  template_selection = UNINITIALIZED_TEMPLATE;
}

void HEXSTRING_template::copy_template(const HEXSTRING_template& other_value)
{
  switch (other_value.template_selection) {
  case SPECIFIC_VALUE:
    single_value = other_value.single_value;
    break;
  case OMIT_VALUE:
  case ANY_VALUE:
  case ANY_OR_OMIT:
    break;
  case VALUE_LIST:
  case COMPLEMENTED_LIST:
    value_list.n_values = other_value.value_list.n_values;
    value_list.list_value = new HEXSTRING_template[value_list.n_values];
    for (unsigned int i = 0; i < value_list.n_values; i++)
      value_list.list_value[i].copy_template(
        other_value.value_list.list_value[i]);
    break;
  case STRING_PATTERN:
    pattern_value = other_value.pattern_value;
    pattern_value->ref_count++;
    break;
1380
1381
1382
1383
  case DECODE_MATCH:
    dec_match = other_value.dec_match;
    dec_match->ref_count++;
    break;
Elemer Lelik's avatar
Elemer Lelik committed
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
  default:
    TTCN_error("Copying an uninitialized/unsupported hexstring template.");
  }
  set_selection(other_value);
}

/*
 This is the same algorithm that match_array uses
 to match 'record of' types.
 The only differences are: how two elements are matched and
 how an asterisk or ? is identified in the template
 */
boolean HEXSTRING_template::match_pattern(
  const hexstring_pattern_struct *string_pattern,
  const HEXSTRING::hexstring_struct *string_value)
{
  // the empty pattern matches the empty hexstring only
  if (string_pattern->n_elements == 0) return string_value->n_nibbles == 0;

  int value_index = 0;
  unsigned int template_index = 0;
  int last_asterisk = -1;
  int last_value_to_asterisk = -1;
  //the following variables are just to speed up the function
  unsigned char pattern_element;
  unsigned char octet;
  unsigned char hex_digit;

  for (;;) {
    pattern_element = string_pattern->elements_ptr[template_index];
    if (pattern_element < 16) {
      octet = string_value->nibbles_ptr[value_index / 2];
      if (value_index % 2)
        hex_digit = octet >> 4;
      else
        hex_digit = octet & 0x0F;
      if (hex_digit == pattern_element) {
        value_index++;
        template_index++;
      }
      else {
        if (last_asterisk == -1) return FALSE;
        template_index = last_asterisk + 1;
        value_index = ++last_value_to_asterisk;
      }
    }
    else if (pattern_element == 16) {//?
      value_index++;
      template_index++;
    }
    else if (pattern_element == 17) {//*
      last_asterisk = template_index++;
      last_value_to_asterisk = value_index;
    }
    else
      TTCN_error("Internal error: invalid element in a hexstring "
        "pattern.");

    if (value_index == string_value->n_nibbles && template_index
      == string_pattern->n_elements) {
      return TRUE;
    }
    else if (template_index == string_pattern->n_elements) {
      if (string_pattern->elements_ptr[template_index - 1] == 17) {
        return TRUE;
      }
      else if (last_asterisk == -1) {
        return FALSE;
      }
      else {
        template_index = last_asterisk + 1;
        value_index = ++last_value_to_asterisk;
      }
    }
    else if (value_index == string_value->n_nibbles) {
      while (template_index < string_pattern->n_elements
        && string_pattern->elements_ptr[template_index] == 17)
        template_index++;

      return template_index == string_pattern->n_elements;
    }
  }
}

HEXSTRING_template::HEXSTRING_template()
{
}

HEXSTRING_template::HEXSTRING_template(template_sel other_value) :
  Restricted_Length_Template(other_value)
{
  check_single_selection(other_value);
}

HEXSTRING_template::HEXSTRING_template(const HEXSTRING& other_value) :
  Restricted_Length_Template(SPECIFIC_VALUE), single_value(other_value)
{
}

HEXSTRING_template::HEXSTRING_template(const HEXSTRING_ELEMENT& other_value) :
  Restricted_Length_Template(SPECIFIC_VALUE), single_value(other_value)
{
}

HEXSTRING_template::HEXSTRING_template(const OPTIONAL<HEXSTRING>& other_value)
{
  switch (other_value.get_selection()) {
  case OPTIONAL_PRESENT:
    set_selection(SPECIFIC_VALUE);
    single_value = (const HEXSTRING&) other_value;
    break;
  case OPTIONAL_OMIT:
    set_selection(OMIT_VALUE);
    break;
1498
  case OPTIONAL_UNBOUND:
Elemer Lelik's avatar
Elemer Lelik committed
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
    TTCN_error("Creating a hexstring template from an unbound optional field.");
  }
}

HEXSTRING_template::HEXSTRING_template(unsigned int n_elements,
  const unsigned char *pattern_elements) :
  Restricted_Length_Template(STRING_PATTERN)
{
  pattern_value
    = (hexstring_pattern_struct*) Malloc(sizeof(hexstring_pattern_struct) + n_elements - 1);
  pattern_value->ref_count = 1;
  pattern_value->n_elements = n_elements;
  memcpy(pattern_value->elements_ptr, pattern_elements, n_elements);
}

HEXSTRING_template::HEXSTRING_template(const HEXSTRING_template& other_value) :
  Restricted_Length_Template()
{
  copy_template(other_value);
}

HEXSTRING_template::~HEXSTRING_template()
{
  clean_up();
}

HEXSTRING_template& HEXSTRING_template::operator=(template_sel other_value)
{
  check_single_selection(other_value);
  clean_up();
  set_selection(other_value);
  return *this;
}

HEXSTRING_template& HEXSTRING_template::operator=(const HEXSTRING& other_value)
{
  other_value.must_bound("Assignment of an unbound hexstring value to a "
    "template.");
  clean_up();
  set_selection(SPECIFIC_VALUE);
  single_value = other_value;
  return *this;
}

HEXSTRING_template& HEXSTRING_template::operator=(
  const HEXSTRING_ELEMENT& other_value)
{
  other_value.must_bound("Assignment of an unbound hexstring element to a "
    "template.");
  clean_up();
  set_selection(SPECIFIC_VALUE);
  single_value = other_value;
  return *this;
}

HEXSTRING_template& HEXSTRING_template::operator=(
  const OPTIONAL<HEXSTRING>& other_value)
{
  clean_up();
  switch (other_value.get_selection()) {
  case OPTIONAL_PRESENT:
    set_selection(SPECIFIC_VALUE);
    single_value = (const HEXSTRING&) other_value;
    break;
  case OPTIONAL_OMIT:
    set_selection(OMIT_VALUE);
    break;
1566
  case OPTIONAL_UNBOUND:
Elemer Lelik's avatar
Elemer Lelik committed
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
    TTCN_error("Assignment of an unbound optional field to a hexstring "
      "template.");
  }
  return *this;
}

HEXSTRING_template& HEXSTRING_template::operator=(
  const HEXSTRING_template& other_value)
{
  if (&other_value != this) {
    clean_up();
    copy_template(other_value);
  }
  return *this;
}

1583
#ifdef TITAN_RUNTIME_2
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
void HEXSTRING_template::concat(Vector<unsigned char>& v) const
{
  switch (template_selection) {
  case ANY_VALUE:
  case ANY_OR_OMIT:
    switch (length_restriction_type) {
    case NO_LENGTH_RESTRICTION:
      if (template_selection == ANY_VALUE) {
        // ? => '*'
        if (v.size() == 0 || v[v.size() - 1] != 17) {
          // '**' == '*', so just ignore the second '*'
          v.push_back(17);
        }
      }
      else {
        TTCN_error("Operand of hexstring template concatenation is an "
          "AnyValueOrNone (*) matching mechanism with no length restriction");
      }
      break;
    case RANGE_LENGTH_RESTRICTION:
      if (!length_restriction.range_length.max_length ||
          length_restriction.range_length.max_length != length_restriction.range_length.min_length) {
        TTCN_error("Operand of hexstring template concatenation is an %s "
          "matching mechanism with non-fixed length restriction",
          template_selection == ANY_VALUE ? "AnyValue (?)" : "AnyValueOrNone (*)");
      }
      // else fall through (range length restriction is allowed if the minimum
      // and maximum value are the same)
    case SINGLE_LENGTH_RESTRICTION: {
      // ? length(N) or * length(N) => '??...?' N times
      int len = length_restriction_type == SINGLE_LENGTH_RESTRICTION ?
        length_restriction.single_length : length_restriction.range_length.min_length;
      for (int i = 0; i < len; ++i) {
        v.push_back(16);
      }
      break; }
    }
    break;
  case SPECIFIC_VALUE:
    concat(v, single_value);
    break;
  case STRING_PATTERN:
    for (unsigned int i = 0; i < pattern_value->n_elements; ++i) {
      v.push_back(pattern_value->elements_ptr[i]);
    }
    break;
  default:
    TTCN_error("Operand of hexstring template concatenation is an "
      "uninitialized or unsupported template.");
  }
}

void HEXSTRING_template::concat(Vector<unsigned char>& v, const HEXSTRING& val)
{
  if (!val.is_bound()) {
    TTCN_error("Operand of hexstring template concatenation is an "
      "unbound value.");
  }
  for (int i = 0; i < val.val_ptr->n_nibbles; ++i) {
    v.push_back(val.get_nibble(i));
  }
}

void HEXSTRING_template::concat(Vector<unsigned char>& v, template_sel sel)
{
  if (sel == ANY_VALUE) {
    // ? => '*'
    if (v.size() == 0 || v[v.size() - 1] != 17) {
      // '**' == '*', so just ignore the second '*'
      v.push_back(17);
    }
  }
  else {
    TTCN_error("Operand of hexstring template concatenation is an "
      "uninitialized or unsupported template.");
  }
}


HEXSTRING_template HEXSTRING_template::operator+(
  const HEXSTRING_template& other_value) const
{
  if (template_selection == SPECIFIC_VALUE &&
      other_value.template_selection == SPECIFIC_VALUE) {
    // result is a specific value template
    return single_value + other_value.single_value;
  }
  if (template_selection == ANY_VALUE &&
      other_value.template_selection == ANY_VALUE &&
      length_restriction_type == NO_LENGTH_RESTRICTION &&
      other_value.length_restriction_type == NO_LENGTH_RESTRICTION) {
    // special case: ? & ? => ?
    return HEXSTRING_template(ANY_VALUE);
  }
  // otherwise the result is an hexstring pattern
  Vector<unsigned char> v;
  concat(v);
  other_value.concat(v);
  return HEXSTRING_template(v.size(), v.data_ptr());
}

HEXSTRING_template HEXSTRING_template::operator+(
  const HEXSTRING& other_value) const
{
  if (template_selection == SPECIFIC_VALUE) {
    // result is a specific value template
    return single_value + other_value;
  }
  // otherwise the result is an hexstring pattern
  Vector<unsigned char> v;
  concat(v);
  concat(v, other_value);
  return HEXSTRING_template(v.size(), v.data_ptr());
}

HEXSTRING_template HEXSTRING_template::operator+(
  const HEXSTRING_ELEMENT& other_value) const
{
  return *this + HEXSTRING(other_value);
}

HEXSTRING_template HEXSTRING_template::operator+(
  template_sel other_template_sel) const
{
  if (template_selection == ANY_VALUE && other_template_sel == ANY_VALUE &&
      length_restriction_type == NO_LENGTH_RESTRICTION) {
    // special case: ? & ? => ?
    return HEXSTRING_template(ANY_VALUE);
  }
  // the result is always an hexstring pattern
  Vector<unsigned char> v;
  concat(v);
  concat(v, other_template_sel);
  return HEXSTRING_template(v.size(), v.data_ptr());
}

HEXSTRING_template operator+(const HEXSTRING& left_value,
  const HEXSTRING_template& right_template)
{
  if (right_template.template_selection == SPECIFIC_VALUE) {
    // result is a specific value template
    return left_value + right_template.single_value;
  }
  // otherwise the result is an hexstring pattern
  Vector<unsigned char> v;
  HEXSTRING_template::concat(v, left_value);
  right_template.concat(v);
  return HEXSTRING_template(v.size(), v.data_ptr());
}

HEXSTRING_template operator+(const HEXSTRING_ELEMENT& left_value,
  const HEXSTRING_template& right_template)
{
  return HEXSTRING(left_value) + right_template;
}

HEXSTRING_template operator+(template_sel left_template_sel,
  const HEXSTRING_template& right_template)
{
  if (left_template_sel == ANY_VALUE &&
      right_template.template_selection == ANY_VALUE &&
      right_template.length_restriction_type ==
      Restricted_Length_Template::NO_LENGTH_RESTRICTION) {
    // special case: ? & ? => ?
    return HEXSTRING_template(ANY_VALUE);
  }
  // the result is always an hexstring pattern
  Vector<unsigned char> v;
  HEXSTRING_template::concat(v, left_template_sel);
  right_template.concat(v);
  return HEXSTRING_template(v.size(), v.data_ptr());
}

HEXSTRING_template operator+(const HEXSTRING& left_value,
  template_sel right_template_sel)
{
  // the result is always an hexstring pattern
  Vector<unsigned char> v;
  HEXSTRING_template::concat(v, left_value);
  HEXSTRING_template::concat(v, right_template_sel);
  return HEXSTRING_template(v.size(), v.data_ptr());
}

HEXSTRING_template operator+(const HEXSTRING_ELEMENT& left_value,
  template_sel right_template_sel)
{
  return HEXSTRING(left_value) + right_template_sel;
}

HEXSTRING_template operator+(template_sel left_template_sel,
  const HEXSTRING& right_value)
{
  // the result is always an hexstring pattern
  Vector<unsigned char> v;
  HEXSTRING_template::concat(v, left_template_sel);
  HEXSTRING_template::concat(v, right_value);
  return HEXSTRING_template(v.size(), v.data_ptr());
}

HEXSTRING_template operator+(template_sel left_template_sel,
  const HEXSTRING_ELEMENT& right_value)
{
  return left_template_sel + HEXSTRING(right_value);
}
1788
#endif // TITAN_RUNTIME_2
1789

Elemer Lelik's avatar
Elemer Lelik committed
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
HEXSTRING_ELEMENT HEXSTRING_template::operator[](int index_value)
{
  if (template_selection != SPECIFIC_VALUE || is_ifpresent)
    TTCN_error("Accessing a hexstring element of a non-specific hexstring "
               "template.");
  return single_value[index_value];
}

HEXSTRING_ELEMENT HEXSTRING_template::operator[](const INTEGER& index_value)
{
  index_value.must_bound("Indexing a hexstring template with an unbound "
                         "integer value.");
  return (*this)[(int)index_value];
}

const HEXSTRING_ELEMENT HEXSTRING_template::operator[](int index_value) const
{
  if (template_selection != SPECIFIC_VALUE || is_ifpresent)
    TTCN_error("Accessing a hexstring element of a non-specific hexstring "
               "template.");
  return single_value[index_value];
}

const HEXSTRING_ELEMENT HEXSTRING_template::operator[](const INTEGER& index_value) const
{
  index_value.must_bound("Indexing a hexstring template with an unbound "
                         "integer value.");
  return (*this)[(int)index_value];
}

Elemer Lelik's avatar
Elemer Lelik committed
1820
1821
boolean HEXSTRING_template::match(const HEXSTRING& other_value,
                                  boolean /* legacy */) const
Elemer Lelik's avatar
Elemer Lelik committed
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
{
  if (!other_value.is_bound()) return FALSE;
  if (!match_length(other_value.val_ptr->n_nibbles)) return FALSE;
  switch (template_selection) {
  case SPECIFIC_VALUE:
    return single_value == other_value;
  case OMIT_VALUE:
    return FALSE;
  case ANY_VALUE:
  case ANY_OR_OMIT:
    return TRUE;
  case VALUE_LIST:
  case COMPLEMENTED_LIST:
    for (unsigned int i = 0; i < value_list.n_values; i++)
      if (value_list.list_value[i].match(other_value)) return template_selection
        == VALUE_LIST;
    return template_selection == COMPLEMENTED_LIST;
  case STRING_PATTERN:
    return match_pattern(pattern_value, other_value.val_ptr);
1841
1842
1843
1844
1845
1846
1847
1848
1849
  case DECODE_MATCH: {
    TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING);
    TTCN_EncDec::clear_error();
    OCTETSTRING os(hex2oct(other_value));
    TTCN_Buffer buff(os);
    boolean ret_val = dec_match->instance->match(buff);
    TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL,TTCN_EncDec::EB_DEFAULT);
    TTCN_EncDec::clear_error();
    return ret_val; }
Elemer Lelik's avatar
Elemer Lelik committed
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
  default:
    TTCN_error("Matching an uninitialized/unsupported hexstring template.");
  }
  return FALSE;
}

const HEXSTRING& HEXSTRING_template::valueof() const
{
  if (template_selection != SPECIFIC_VALUE || is_ifpresent) TTCN_error(
    "Performing a valueof or send operation on a non-specific "
      "hexstring template.");
  return single_value;
}

int HEXSTRING_template::lengthof() const
{
  int min_length;
  boolean has_any_or_none;
  if (is_ifpresent) TTCN_error(
    "Performing lengthof() operation on a hexstring template "
      "which has an ifpresent attribute.");
  switch (template_selection) {
  case SPECIFIC_VALUE:
    min_length = single_value.lengthof();
    has_any_or_none = FALSE;
    break;
  case OMIT_VALUE:
    TTCN_error("Performing lengthof() operation on a hexstring template "
      "containing omit value.");
  case ANY_VALUE:
  case ANY_OR_OMIT:
    min_length = 0;
    has_any_or_none = TRUE; // max. length is infinity
    break;
  case VALUE_LIST: {
    // error if any element does not have length or the lengths differ
    if (value_list.n_values < 1) TTCN_error("Internal error: "
      "Performing lengthof() operation on a hexstring template "
      "containing an empty list.");
    int item_length = value_list.list_value[0].lengthof();
    for (unsigned int i = 1; i < value_list.n_values; i++) {
      if (value_list.list_value[i].lengthof() != item_length) TTCN_error(
        "Performing lengthof() operation on a hexstring template "
          "containing a value list with different lengths.");
    }
    min_length = item_length;
    has_any_or_none = FALSE;
    break;
  }
  case COMPLEMENTED_LIST:
    TTCN_error("Performing lengthof() operation on a hexstring template "
      "containing complemented list.");
  case STRING_PATTERN:
    min_length = 0;
    has_any_or_none = FALSE; // TRUE if * chars in the pattern
    for (unsigned int i = 0; i < pattern_value->n_elements; i++) {
      if (pattern_value->elements_ptr[i] < 17)
        min_length++; // case of 0-F, ?
      else
        has_any_or_none = TRUE; // case of * character
    }
    break;
  default:
    TTCN_error("Performing lengthof() operation on an "
      "uninitialized/unsupported hexstring template.");
  }
  return check_section_is_single(min_length, has_any_or_none, "length", "a",
    "hexstring template");
}

void HEXSTRING_template::set_type(template_sel template_type,
  unsigned int list_length)
{
1923
1924
  if (template_type != VALUE_LIST && template_type != COMPLEMENTED_LIST &&
      template_type != DECODE_MATCH) TTCN_error(
Elemer Lelik's avatar
Elemer Lelik committed
1925
1926
1927
    "Setting an invalid list type for a hexstring template.");
  clean_up();
  set_selection(template_type);
1928
1929
1930
1931
  if (template_type != DECODE_MATCH) {
    value_list.n_values = list_length;
    value_list.list_value = new HEXSTRING_template[list_length];
  }
Elemer Lelik's avatar
Elemer Lelik committed
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
}

HEXSTRING_template& HEXSTRING_template::list_item(unsigned int list_index)
{
  if (template_selection != VALUE_LIST && template_selection
    != COMPLEMENTED_LIST) TTCN_error(
    "Accessing a list element of a non-list hexstring template.");
  if (list_index >= value_list.n_values) TTCN_error(
    "Index overflow in a hexstring value list template.");
  return value_list.list_value[list_index];
}

1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
void HEXSTRING_template::set_decmatch(Dec_Match_Interface* new_instance)
{
  if (template_selection != DECODE_MATCH) {
    TTCN_error("Setting the decoded content matching mechanism of a non-decmatch "
      "hexstring template.");
  }
  dec_match = new decmatch_struct;
  dec_match->ref_count = 1;
  dec_match->instance = new_instance;
}

1955
1956
1957
1958
1959
1960
1961
1962
1963
void* HEXSTRING_template::get_decmatch_dec_res() const
{
  if (template_selection != DECODE_MATCH) {
    TTCN_error("Retrieving the decoding result of a non-decmatch hexstring "
      "template.");
  }
  return dec_match->instance->get_dec_res();
}

1964
1965
1966
1967
1968
1969
1970
1971
1972
const TTCN_Typedescriptor_t* HEXSTRING_template::get_decmatch_type_descr() const
{
  if (template_selection != DECODE_MATCH) {
    TTCN_error("Retrieving the decoded type's descriptor in a non-decmatch "
      "hexstring template.");
  }
  return dec_match->instance->get_type_descr();
}

Elemer Lelik's avatar
Elemer Lelik committed
1973
1974
1975
1976
1977
1978
1979
void HEXSTRING_template::log() const
{
  switch (template_selection) {
  case SPECIFIC_VALUE:
    single_value.log();
    break;
  case COMPLEMENTED_LIST:
1980
    TTCN_Logger::log_event_str("complement");
Elemer Lelik's avatar
Elemer Lelik committed
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
    // no break
  case VALUE_LIST:
    TTCN_Logger::log_char('(');
    for (unsigned int i = 0; i < value_list.n_values; i++) {
      if (i > 0) TTCN_Logger::log_event_str(", ");
      value_list.list_value[i].log();
    }
    TTCN_Logger::log_char(')');
    break;
  case STRING_PATTERN:
    TTCN_Logger::log_char('\'');
    for (unsigned int i = 0; i < pattern_value->n_elements; i++) {
      unsigned char pattern = pattern_value->elements_ptr[i];
      if (pattern < 16)
        TTCN_Logger::log_hex(pattern);
      else if (pattern == 16)
        TTCN_Logger::log_char('?');
      else if (pattern == 17)
        TTCN_Logger::log_char('*');
      else
        TTCN_Logger::log_event_str("<unknown>");
    }
    TTCN_Logger::log_event_str("'H");
    break;
2005
2006
2007
2008
  case DECODE_MATCH:
    TTCN_Logger::log_event_str("decmatch ");
    dec_match->instance->log();
    break;
Elemer Lelik's avatar
Elemer Lelik committed
2009
2010
2011
2012
2013
2014
2015
2016
  default:
    log_generic();
    break;
  }
  log_restricted();
  log_ifpresent();
}

Elemer Lelik's avatar
Elemer Lelik committed
2017
2018
void HEXSTRING_template::log_match(const HEXSTRING& match_value,
                                   boolean /* legacy */) const
Elemer Lelik's avatar
Elemer Lelik committed
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
{
  if (TTCN_Logger::VERBOSITY_COMPACT == TTCN_Logger::get_matching_verbosity()
    && TTCN_Logger::get_logmatch_buffer_len() != 0) {
    TTCN_Logger::print_logmatch_buffer();
    TTCN_Logger::log_event_str(" := ");
  }
  match_value.log();
  TTCN_Logger::log_event_str(" with ");
  log();
  if (match(match_value))
    TTCN_Logger::log_event_str(" matched");
  else
    TTCN_Logger::log_event_str(" unmatched");
}

void HEXSTRING_template::set_param(Module_Param& param) {
  param.basic_check(Module_Param::BC_TEMPLATE|Module_Param::BC_LIST, "hexstring template");
Elemer Lelik's avatar
Elemer Lelik committed
2036
  Module_Param_Ptr mp = &param;
2037
#ifdef TITAN_RUNTIME_2
Elemer Lelik's avatar
Elemer Lelik committed
2038
2039
2040
  if (param.get_type() == Module_Param::MP_Reference) {
    mp = param.get_referenced_param();
  }
2041
#endif
Elemer Lelik's avatar
Elemer Lelik committed
2042
  switch (mp->get_type()) {
Elemer Lelik's avatar
Elemer Lelik committed
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
  case Module_Param::MP_Omit:
    *this = OMIT_VALUE;
    break;
  case Module_Param::MP_Any:
    *this = ANY_VALUE;
    break;
  case Module_Param::MP_AnyOrNone:
    *this = ANY_OR_OMIT;
    break;
  case Module_Param::MP_List_Template:
Elemer Lelik's avatar
Elemer Lelik committed
2053
2054
2055
2056
2057
2058
  case Module_Param::MP_ComplementList_Template: {
    HEXSTRING_template temp;
    temp.set_type(mp->get_type() == Module_Param::MP_List_Template ?
      VALUE_LIST : COMPLEMENTED_LIST, mp->get_size());
    for (size_t i=0; i<mp->get_size(); i++) {
      temp.list_item(i).set_param(*mp->get_elem(i));
Elemer Lelik's avatar
Elemer Lelik committed
2059
    }
Elemer Lelik's avatar
Elemer Lelik committed
2060
2061
    *this = temp;
    break; }
Elemer Lelik's avatar
Elemer Lelik committed
2062
  case Module_Param::MP_Hexstring:
Elemer Lelik's avatar
Elemer Lelik committed
2063
    *this = HEXSTRING(mp->get_string_size(), (unsigned char*)mp->get_string_data());
Elemer Lelik's avatar
Elemer Lelik committed
2064
2065
    break;
  case Module_Param::MP_Hexstring_Template:
Elemer Lelik's avatar
Elemer Lelik committed
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
    *this = HEXSTRING_template(mp->get_string_size(), (unsigned char*)mp->get_string_data());
    break;
  case Module_Param::MP_Expression:
    if (mp->get_expr_type() == Module_Param::EXPR_CONCATENATE) {
      HEXSTRING operand1, operand2;
      operand1.set_param(*mp->get_operand1());
      operand2.set_param(*mp->get_operand2());
      *this = operand1 + operand2;
    }
    else {
Botond Baranyi's avatar
Botond Baranyi committed
2076
      param.expr_type_error("a hexstring");
Elemer Lelik's avatar
Elemer Lelik committed
2077
    }
Elemer Lelik's avatar
Elemer Lelik committed
2078
2079
2080
2081
    break;
  default:
    param.type_error("hexstring template");
  }
Elemer Lelik's avatar
Elemer Lelik committed
2082
2083
2084
2085
2086
2087
2088
2089
2090
  is_ifpresent = param.get_ifpresent() || mp->get_ifpresent();
  if (param.get_length_restriction() != NULL) {
    set_length_range(param);
  }
  else {
    set_length_range(*mp);
  }
}

2091
#ifdef TITAN_RUNTIME_2
Elemer Lelik's avatar
Elemer Lelik committed
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
Module_Param* HEXSTRING_template::get_param(Module_Param_Name& param_name) const
{
  Module_Param* mp = NULL;
  switch (template_selection) {
  case UNINITIALIZED_TEMPLATE:
    mp = new Module_Param_Unbound();
    break;
  case OMIT_VALUE:
    mp = new Module_Param_Omit();
    break;
  case ANY_VALUE:
    mp = new Module_Param_Any();
    break;
  case ANY_OR_OMIT:
    mp = new Module_Param_AnyOrNone();
    break;
  case SPECIFIC_VALUE:
    mp = single_value.get_param(param_name);
    break;
  case VALUE_LIST:
  case COMPLEMENTED_LIST: {
    if (template_selection == VALUE_LIST) {
      mp = new Module_Param_List_Template();
    }
    else {
      mp = new Module_Param_ComplementList_Template();
    }
    for (size_t i = 0; i < value_list.n_values; ++i) {
      mp->add_elem(value_list.list_value[i].get_param(param_name));
    }
    break; }
  case STRING_PATTERN: {
    unsigned char* val_cpy = (unsigned char*)Malloc(pattern_value->n_elements);
    memcpy(val_cpy, pattern_value->elements_ptr, pattern_value->n_elements);
    mp = new Module_Param_Hexstring_Template(pattern_value->n_elements, val_cpy);
    break; }
2128
  case DECODE_MATCH:
2129
    TTCN_error("Referencing a decoded content matching template is not supported.");
2130
    break;
Elemer Lelik's avatar
Elemer Lelik committed
2131
  default:
2132
    TTCN_error("Referencing an uninitialized/unsupported hexstring template.");
Elemer Lelik's avatar
Elemer Lelik committed
2133
2134
2135
2136
2137
2138
<