-
Notifications
You must be signed in to change notification settings - Fork 356
/
vcd.c
2170 lines (1968 loc) · 64.8 KB
/
vcd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
426
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
604
605
606
607
608
609
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
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
854
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
900
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
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
973
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
/*
* This file is part of the libsigrok project.
*
* Copyright (C) 2012 Petteri Aimonen <jpa@sr.mail.kapsi.fi>
* Copyright (C) 2014 Bert Vermeulen <bert@biot.com>
* Copyright (C) 2017-2020 Gerhard Sittig <gerhard.sittig@gmx.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* The VCD input module has the following options. See the options[]
* declaration near the bottom of the input module's source file.
*
* numchannels: Maximum number of sigrok channels to create. VCD signals
* are detected in their order of declaration in the VCD file header,
* and mapped to sigrok channels.
*
* skip: Allows to skip data at the start of the input file. This can
* speed up operation on long captures.
* Value < 0: Skip until first timestamp that is listed in the file.
* (This is the default behaviour.)
* Value = 0: Do not skip, instead generate samples beginning from
* timestamp 0.
* Value > 0: Start at the given timestamp.
*
* samplerate: overwrite/manually specify the samplerate for this VCD file
* and ignore timescale sections.
*
* downsample: Divide the samplerate by the given factor. This can
* speed up operation on long captures.
*
* compress: Trim idle periods which are longer than this value to span
* only this many timescale ticks. This can speed up operation on long
* captures (default 0, don't compress).
*
* Based on Verilog standard IEEE Std 1364-2001 Version C
*
* Supported features:
* - $var with 'wire', 'reg' and 'logic' types of scalar variables
* - $timescale definition for samplerate
* - multiple character variable identifiers
* - same identifer used for multiple signals (identical values)
* - vector variables (bit vectors)
* - integer variables (analog signals with 0 digits, passed as single
* precision float number)
* - real variables (analog signals, passed on with single precision,
* arbitrary digits value, not user adjustable)
* - nested $scope, results in prefixed sigrok channel names
*
* Most important unsupported features:
* - $dumpvars initial value declaration (is not an issue if generators
* provide sample data for the #0 timestamp, otherwise session data
* starts from zero values, and catches up when the signal changes its
* state to a supported value)
*
* Implementor's note: This input module specifically does _not_ use
* glib routines where they would hurt performance. Lots of memory
* allocations increase execution time not by percents but by huge
* factors. This motivated this module's custom code for splitting
* words on text lines, and pooling previously allocated buffers.
*
* TODO (in arbitrary order)
* - Map VCD scopes to sigrok channel groups?
* - Does libsigrok support nested channel groups? Or is this feature
* exclusive to Pulseview?
* - Check VCD input to VCD output behaviour. Verify that export and
* re-import results in identical data (well, VCD's constraints on
* timescale values is known to result in differences).
* - Check the minimum timestamp delta in the input data set, suggest
* the downsample=N option to users for reduced resource consumption.
* Popular VCD file creation utilities love to specify insanely tiny
* timescale values in the pico or even femto seconds range. Which
* results in huge sample counts after import, and potentially even
* terminates the application due to resource exhaustion. This issue
* only will vanish when common libsigrok infrastructure no longer
* depends on constant rate streams of samples at discrete points
* in time. The current input module implementation has code in place
* to gather timestamp statistics, but the most appropriate condition
* when to notify users is yet to be found.
* - Cleanup the implementation.
* - Consistent use of the glib API (where appropriate).
* - More appropriate variable/function identifiers.
* - More robust handling of multi-word input phrases and chunked
* input buffers? This implementation assumes that e.g. b[01]+
* patterns are complete when they start, and the signal identifier
* is available as well. Which may be true assuming that input data
* comes in complete text lines.
* - See if other input modules have learned lessons that we could
* benefit from here as well? Pointless BOM (done), line oriented
* processing with EOL variants and with optional last EOL, module
* state reset and file re-read (stable channels list), buffered
* session feed, synchronized feed for mixed signal sources, digits
* or formats support for analog input, single vs double precision,
* etc.
* - Re-consider logging. Verbosity levels should be acceptable,
* but volume is an issue. Drop duplicates, and drop messages from
* known good code paths.
*/
#include <config.h>
#include <glib.h>
#include <libsigrok/libsigrok.h>
#include "libsigrok-internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LOG_PREFIX "input/vcd"
#define CHUNK_SIZE (4 * 1024 * 1024)
#define SCOPE_SEP '.'
struct context {
struct vcd_user_opt {
size_t maxchannels; /* sigrok channels (output) */
uint64_t samplerate;
uint64_t downsample;
uint64_t compress;
uint64_t skip_starttime;
gboolean skip_specified;
} options;
gboolean use_skip;
gboolean started;
gboolean got_header;
uint64_t prev_timestamp;
uint64_t samplerate;
size_t vcdsignals; /* VCD signals (input) */
GSList *ignored_signals;
gboolean data_after_timestamp;
gboolean ignore_end_keyword;
gboolean skip_until_end;
GSList *channels;
size_t unit_size;
size_t logic_count;
size_t analog_count;
uint8_t *current_logic;
float *current_floats;
struct {
size_t max_bits;
size_t unit_size;
uint8_t *value;
size_t sig_count;
} conv_bits;
GString *scope_prefix;
struct feed_queue_logic *feed_logic;
struct ts_stats {
size_t total_ts_seen;
uint64_t last_ts_value;
uint64_t last_ts_delta;
size_t min_count;
struct {
uint64_t delta;
size_t count;
} min_items[2];
uint32_t early_check_shift;
size_t early_last_emitted;
} ts_stats;
struct vcd_prev {
GSList *sr_channels;
GSList *sr_groups;
} prev;
};
struct vcd_channel {
char *name;
char *identifier;
size_t size;
enum sr_channeltype type;
size_t array_index;
size_t byte_idx;
uint8_t bit_mask;
char *base_name;
size_t range_lower, range_upper;
int submit_digits;
struct feed_queue_analog *feed_analog;
};
static void free_channel(void *data)
{
struct vcd_channel *vcd_ch;
vcd_ch = data;
if (!vcd_ch)
return;
g_free(vcd_ch->name);
g_free(vcd_ch->identifier);
g_free(vcd_ch->base_name);
feed_queue_analog_free(vcd_ch->feed_analog);
g_free(vcd_ch);
}
/*
* Another timestamp delta was observed, update statistics: Update the
* sorted list of minimum values, and increment the occurance counter.
* Returns the position of the item's statistics slot, or returns a huge
* invalid index when the current delta is larger than previously found
* values.
*/
static size_t ts_stats_update_min(struct ts_stats *stats, uint64_t delta)
{
size_t idx, copy_idx;
/* Advance over previously recorded values which are smaller. */
idx = 0;
while (idx < stats->min_count && stats->min_items[idx].delta < delta)
idx++;
if (idx == ARRAY_SIZE(stats->min_items))
return idx;
/* Found the exact value that previously was registered? */
if (stats->min_items[idx].delta == delta) {
stats->min_items[idx].count++;
return idx;
}
/* Allocate another slot, bubble up larger values as needed. */
if (stats->min_count < ARRAY_SIZE(stats->min_items))
stats->min_count++;
for (copy_idx = stats->min_count - 1; copy_idx > idx; copy_idx--)
stats->min_items[copy_idx] = stats->min_items[copy_idx - 1];
/* Start tracking this value in the found or freed slot. */
memset(&stats->min_items[idx], 0, sizeof(stats->min_items[idx]));
stats->min_items[idx].delta = delta;
stats->min_items[idx].count++;
return idx;
}
/*
* Intermediate check for extreme oversampling in the input data. Rate
* limited emission of warnings to avoid noise, "late" emission of the
* first potential message to avoid false positives, yet need to emit
* the messages early (*way* before EOF) to raise awareness.
*
* TODO
* Tune the limits, improve perception and usefulness of these checks.
* Need to start emitting messages soon enough to be seen by users. Yet
* avoid unnecessary messages for valid input's idle/quiet phases. Slow
* input transitions are perfectly legal before bursty phases are seen
* in the input data. Needs the check become an option, on by default,
* but suppressable by users?
*/
static void ts_stats_check_early(struct ts_stats *stats)
{
static const struct {
uint64_t delta;
size_t count;
} *cp, check_points[] = {
{ 100, 1000000, }, /* Still x100 after 1mio transitions. */
{ 1000, 100000, }, /* Still x1k after 100k transitions. */
{ 10000, 10000, }, /* Still x10k after 10k transitions. */
{ 1000000, 2500, }, /* Still x1m after 2.5k transitions. */
};
size_t cp_idx;
uint64_t seen_delta, check_delta;
size_t seen_count;
/* Get the current minimum's value and count. */
if (!stats->min_count)
return;
seen_delta = stats->min_items[0].delta;
seen_count = stats->min_items[0].count;
/* Emit at most one weak message per import. */
if (stats->early_last_emitted)
return;
/* Check arbitrary marks, emit rate limited warnings. */
(void)seen_count;
check_delta = seen_delta >> stats->early_check_shift;
for (cp_idx = 0; cp_idx < ARRAY_SIZE(check_points); cp_idx++) {
cp = &check_points[cp_idx];
/* No other match can happen below. Done iterating. */
if (stats->total_ts_seen > cp->count)
return;
/* Advance to the next checkpoint description. */
if (stats->total_ts_seen != cp->count)
continue;
/* First occurance of that timestamp count. Check the value. */
sr_dbg("TS early chk: total %zu, min delta %" PRIu64 " / %" PRIu64 ".",
cp->count, seen_delta, check_delta);
if (check_delta < cp->delta)
return;
sr_warn("Low change rate? (weak estimate, min TS delta %" PRIu64 " after %zu timestamps)",
seen_delta, stats->total_ts_seen);
sr_warn("Consider using the downsample=N option, or increasing its value.");
stats->early_last_emitted = stats->total_ts_seen;
return;
}
}
/* Reset the internal state of the timestamp tracker. */
static int ts_stats_prep(struct context *inc)
{
struct ts_stats *stats;
uint64_t down_sample_value;
uint32_t down_sample_shift;
stats = &inc->ts_stats;
memset(stats, 0, sizeof(*stats));
down_sample_value = inc->options.downsample;
down_sample_shift = 0;
while (down_sample_value >= 2) {
down_sample_shift++;
down_sample_value /= 2;
}
stats->early_check_shift = down_sample_shift;
return SR_OK;
}
/* Inspect another timestamp that was received. */
static int ts_stats_check(struct ts_stats *stats, uint64_t curr_ts)
{
uint64_t last_ts, delta;
last_ts = stats->last_ts_value;
stats->last_ts_value = curr_ts;
stats->total_ts_seen++;
if (stats->total_ts_seen < 2)
return SR_OK;
delta = curr_ts - last_ts;
stats->last_ts_delta = delta;
(void)ts_stats_update_min(stats, delta);
ts_stats_check_early(stats);
return SR_OK;
}
/* Postprocess internal timestamp tracker state. */
static int ts_stats_post(struct context *inc, gboolean ignore_terminal)
{
struct ts_stats *stats;
size_t min_idx;
uint64_t delta, over_sample, over_sample_scaled, suggest_factor;
enum sr_loglevel log_level;
gboolean is_suspicious, has_downsample;
stats = &inc->ts_stats;
/*
* Lookup the smallest timestamp delta which was found during
* data import. Ignore the last delta if its timestamp was never
* followed by data, and this was the only occurance. Absence of
* result data is non-fatal here -- this code exclusively serves
* to raise users' awareness of potential pitfalls, but does not
* change behaviour of data processing.
*
* TODO Also filter by occurance count? To not emit warnings when
* captured signals only change slowly by design. Only warn when
* the sample rate and samples count product exceeds a threshold?
* See below for the necessity (and potential) to adjust the log
* message's severity and content.
*/
min_idx = 0;
if (ignore_terminal) do {
if (min_idx >= stats->min_count)
break;
delta = stats->last_ts_delta;
if (stats->min_items[min_idx].delta != delta)
break;
if (stats->min_items[min_idx].count != 1)
break;
min_idx++;
} while (0);
if (min_idx >= stats->min_count)
return SR_OK;
/*
* TODO Refine the condition whether to notify the user, and
* which severity to use after having inspected all input data.
* Any detail could get involved which previously was gathered
* during data processing: total sample count, channel count
* including their data type and bits width, the oversampling
* factor (minimum observed "change rate"), or any combination
* thereof. The current check is rather simple (unconditional
* warning for ratios starting at 100, regardless of sample or
* channel count).
*/
over_sample = stats->min_items[min_idx].delta;
over_sample_scaled = over_sample / inc->options.downsample;
sr_dbg("TS post stats: oversample unscaled %" PRIu64 ", scaled %" PRIu64,
over_sample, over_sample_scaled);
if (over_sample_scaled < 10) {
sr_dbg("TS post stats: Low oversampling ratio, good.");
return SR_OK;
}
/*
* Avoid constructing the message from several tiny pieces by
* design, because this would be hard on translators. Stick with
* complete sentences instead, and accept the redundancy in the
* user's interest.
*/
log_level = (over_sample_scaled > 20) ? SR_LOG_WARN : SR_LOG_INFO;
is_suspicious = over_sample_scaled > 20;
if (is_suspicious) {
sr_log(log_level, LOG_PREFIX ": "
"Suspiciously low overall change rate (total min TS delta %" PRIu64 ").",
over_sample_scaled);
} else {
sr_log(log_level, LOG_PREFIX ": "
"Low overall change rate (total min TS delta %" PRIu64 ").",
over_sample_scaled);
}
has_downsample = inc->options.downsample > 1;
suggest_factor = inc->options.downsample;
while (over_sample_scaled >= 10) {
suggest_factor *= 10;
over_sample_scaled /= 10;
}
if (has_downsample) {
sr_log(log_level, LOG_PREFIX ": "
"Suggest higher downsample value, like %" PRIu64 ".",
suggest_factor);
} else {
sr_log(log_level, LOG_PREFIX ": "
"Suggest to downsample, value like %" PRIu64 ".",
suggest_factor);
}
return SR_OK;
}
static void check_remove_bom(GString *buf)
{
static const char *bom_text = "\xef\xbb\xbf";
if (buf->len < strlen(bom_text))
return;
if (strncmp(buf->str, bom_text, strlen(bom_text)) != 0)
return;
g_string_erase(buf, 0, strlen(bom_text));
}
/*
* Reads a single VCD section from input file and parses it to name/contents.
* e.g. $timescale 1ps $end => "timescale" "1ps"
*
* The section (its content and its opening/closing markers) can span
* multiple text lines. This routine must not modify the caller's input
* buffer. Executes potentially multiple times on the same input data,
* and executes outside of the processing of the file's data section.
*/
static gboolean parse_section(GString *buf, char **name, char **contents)
{
static const char *end_text = "$end";
gboolean status;
size_t pos, len;
const char *grab_start, *grab_end;
GString *sname, *scontent;
/* Preset falsy return values. Gets updated below. */
*name = *contents = NULL;
status = FALSE;
/* Skip any initial white-space. */
pos = 0;
while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
pos++;
/* Section tag should start with $. */
if (buf->str[pos++] != '$')
return FALSE;
/* Read the section tag. */
grab_start = &buf->str[pos];
while (pos < buf->len && !g_ascii_isspace(buf->str[pos]))
pos++;
grab_end = &buf->str[pos];
sname = g_string_new_len(grab_start, grab_end - grab_start);
/* Skip whitespace before content. */
while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
pos++;
/* Read the content up to the '$end' marker. */
scontent = g_string_sized_new(128);
grab_start = &buf->str[pos];
grab_end = g_strstr_len(grab_start, buf->len - pos, end_text);
if (grab_end) {
/* Advance 'pos' to after '$end' and more whitespace. */
pos = grab_end - buf->str;
pos += strlen(end_text);
while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
pos++;
/* Grab the (trimmed) content text. */
while (grab_end > grab_start && g_ascii_isspace(grab_end[-1]))
grab_end--;
len = grab_end - grab_start;
g_string_append_len(scontent, grab_start, len);
if (sname->len)
status = TRUE;
/* Consume the input text which just was taken. */
g_string_erase(buf, 0, pos);
}
/* Return section name and content if a section was seen. */
*name = g_string_free(sname, !status);
*contents = g_string_free(scontent, !status);
return status;
}
static gboolean have_header(GString *buf)
{
static const char *enddef_txt = "$enddefinitions";
static const char *end_txt = "$end";
char *p, *p_stop;
/* Search for "end of definitions" section keyword. */
p = g_strstr_len(buf->str, buf->len, enddef_txt);
if (!p)
return FALSE;
p += strlen(enddef_txt);
/*
* Search for end of section (content expected to be empty).
* Uses DIY logic to scan for the literals' presence including
* empty space between keywords. MUST NOT modify the caller's
* input data, potentially executes several times on the same
* receive buffer, and executes outside of the processing the
* file's data section.
*/
p_stop = &buf->str[buf->len];
p_stop -= strlen(end_txt);
while (p < p_stop && g_ascii_isspace(*p))
p++;
if (strncmp(p, end_txt, strlen(end_txt)) != 0)
return FALSE;
p += strlen(end_txt);
return TRUE;
}
static int parse_timescale(struct context *inc, char *contents)
{
uint64_t p, q;
if (inc->options.samplerate != 0) {
sr_info("Ignoring timescale section as the samplerate was manually overwritten!");
return SR_OK;
}
/*
* The standard allows for values 1, 10 or 100
* and units s, ms, us, ns, ps and fs.
*/
if (sr_parse_period(contents, &p, &q) != SR_OK) {
sr_err("Parsing $timescale failed.");
return SR_ERR_DATA;
}
inc->samplerate = q / p;
sr_dbg("Samplerate: %" PRIu64, inc->samplerate);
if (q % p != 0) {
/* Does not happen unless time value is non-standard */
sr_warn("Inexact rounding of samplerate, %" PRIu64 " / %" PRIu64 " to %" PRIu64 " Hz.",
q, p, inc->samplerate);
}
return SR_OK;
}
/*
* Handle '$scope' and '$upscope' sections in the input file. Assume that
* input signals have a "base name", which may be ambiguous within the
* file. These names get declared within potentially nested scopes, which
* this implementation uses to create longer but hopefully unique and
* thus more usable sigrok channel names.
*
* Track the currently effective scopes in a string variable to simplify
* the channel name creation. Start from an empty string, then append the
* scope name and a separator when a new scope opens, and remove the last
* scope name when a scope closes. This allows to simply prefix basenames
* with the current scope to get a full name.
*
* It's an implementation detail to keep the trailing NUL here in the
* GString member, to simplify the g_strconcat() call in the channel name
* creation.
*
* TODO
* - Check whether scope types must get supported, this implementation
* does not distinguish between 'module' and 'begin' and what else
* may be seen. The first word simply gets ignored.
* - Check the allowed alphabet for scope names. This implementation
* assumes "programming language identifier" style (alphanumeric with
* underscores, plus brackets since we've seen them in example files).
*/
static int parse_scope(struct context *inc, char *contents, gboolean is_up)
{
char *sep_pos, *name_pos, *type_pos;
size_t length;
/*
* The 'upscope' case, drop one scope level (if available). Accept
* excess 'upscope' calls, assume that a previous 'scope' section
* was ignored because it referenced our software package's name.
*/
if (is_up) {
/*
* Check for a second right-most separator (and position
* right behind that, which is the start of the last
* scope component), or fallback to the start of string.
* g_string_erase() from that positon to the end to drop
* the last component.
*/
name_pos = inc->scope_prefix->str;
do {
sep_pos = strrchr(name_pos, SCOPE_SEP);
if (!sep_pos)
break;
*sep_pos = '\0';
sep_pos = strrchr(name_pos, SCOPE_SEP);
if (!sep_pos)
break;
name_pos = ++sep_pos;
} while (0);
length = name_pos - inc->scope_prefix->str;
g_string_truncate(inc->scope_prefix, length);
g_string_append_c(inc->scope_prefix, '\0');
sr_dbg("$upscope, prefix now: \"%s\"", inc->scope_prefix->str);
return SR_OK;
}
/*
* The 'scope' case, add another scope level. But skip our own
* package name, assuming that this is an artificial node which
* was emitted by libsigrok's VCD output module.
*/
sr_spew("$scope, got: \"%s\"", contents);
type_pos = sr_text_next_word(contents, &contents);
if (!type_pos) {
sr_err("Cannot parse 'scope' directive");
return SR_ERR_DATA;
}
name_pos = sr_text_next_word(contents, &contents);
if (!name_pos || contents) {
sr_err("Cannot parse 'scope' directive");
return SR_ERR_DATA;
}
if (strcmp(name_pos, PACKAGE_NAME) == 0) {
sr_info("Skipping scope with application's package name: %s",
name_pos);
*name_pos = '\0';
}
if (*name_pos) {
/* Drop NUL, append scope name and separator, and re-add NUL. */
g_string_truncate(inc->scope_prefix, inc->scope_prefix->len - 1);
g_string_append_printf(inc->scope_prefix,
"%s%c%c", name_pos, SCOPE_SEP, '\0');
}
sr_dbg("$scope, prefix now: \"%s\"", inc->scope_prefix->str);
return SR_OK;
}
/**
* Parse a $var section which describes a VCD signal ("variable").
*
* @param[in] inc Input module context.
* @param[in] contents Input text, content of $var section.
*/
static int parse_header_var(struct context *inc, char *contents)
{
char *type, *size_txt, *id, *ref, *idx;
gboolean is_reg, is_wire, is_logic, is_real, is_int;
gboolean is_str;
enum sr_channeltype ch_type;
size_t size, next_size;
struct vcd_channel *vcd_ch;
/*
* Format of $var or $reg header specs:
* $var type size identifier reference [opt-index] $end
*/
type = sr_text_next_word(contents, &contents);
size_txt = sr_text_next_word(contents, &contents);
id = sr_text_next_word(contents, &contents);
ref = sr_text_next_word(contents, &contents);
idx = sr_text_next_word(contents, &contents);
if (idx && !*idx)
idx = NULL;
if (!type || !size_txt || !id || !ref || contents) {
sr_warn("$var section should have 4 or 5 items");
return SR_ERR_DATA;
}
is_reg = g_strcmp0(type, "reg") == 0;
is_wire = g_strcmp0(type, "wire") == 0;
is_logic = g_strcmp0(type, "logic") == 0;
is_real = g_strcmp0(type, "real") == 0;
is_int = g_strcmp0(type, "integer") == 0;
is_str = g_strcmp0(type, "string") == 0;
if (is_reg || is_wire || is_logic) {
ch_type = SR_CHANNEL_LOGIC;
} else if (is_real || is_int) {
ch_type = SR_CHANNEL_ANALOG;
} else if (is_str) {
sr_warn("Skipping id %s, name '%s%s', unsupported type '%s'.",
id, ref, idx ? idx : "", type);
inc->ignored_signals = g_slist_append(inc->ignored_signals,
g_strdup(id));
return SR_OK;
} else {
sr_err("Unsupported signal type: '%s'", type);
return SR_ERR_DATA;
}
size = strtol(size_txt, NULL, 10);
if (ch_type == SR_CHANNEL_ANALOG) {
if (is_real && size != 32 && size != 64) {
/*
* The VCD input module does not depend on the
* specific width of the floating point value.
* This is just for information. Upon value
* changes, a mere string gets converted to
* float, so we may not care at all.
*
* Strictly speaking we might warn for 64bit
* (double precision) declarations, because
* sigrok internally uses single precision
* (32bit) only.
*/
sr_info("Unexpected real width: '%s'", size_txt);
}
/* Simplify code paths below, by assuming size 1. */
size = 1;
}
if (!size) {
sr_warn("Unsupported signal size: '%s'", size_txt);
return SR_ERR_DATA;
}
if (inc->conv_bits.max_bits < size)
inc->conv_bits.max_bits = size;
next_size = inc->logic_count + inc->analog_count + size;
if (inc->options.maxchannels && next_size > inc->options.maxchannels) {
sr_warn("Skipping '%s%s', exceeds requested channel count %zu.",
ref, idx ? idx : "", inc->options.maxchannels);
inc->ignored_signals = g_slist_append(inc->ignored_signals,
g_strdup(id));
return SR_OK;
}
vcd_ch = g_malloc0(sizeof(*vcd_ch));
vcd_ch->identifier = g_strdup(id);
vcd_ch->name = g_strconcat(inc->scope_prefix->str, ref, idx, NULL);
vcd_ch->size = size;
vcd_ch->type = ch_type;
switch (ch_type) {
case SR_CHANNEL_LOGIC:
vcd_ch->array_index = inc->logic_count;
vcd_ch->byte_idx = vcd_ch->array_index / 8;
vcd_ch->bit_mask = 1 << (vcd_ch->array_index % 8);
inc->logic_count += size;
break;
case SR_CHANNEL_ANALOG:
vcd_ch->array_index = inc->analog_count++;
/* TODO: Use proper 'digits' value for this input module. */
vcd_ch->submit_digits = is_real ? 2 : 0;
break;
}
inc->vcdsignals++;
sr_spew("VCD signal %zu '%s' ID '%s' (size %zu), sr type %s, idx %zu.",
inc->vcdsignals, vcd_ch->name,
vcd_ch->identifier, vcd_ch->size,
vcd_ch->type == SR_CHANNEL_ANALOG ? "A" : "L",
vcd_ch->array_index);
inc->channels = g_slist_append(inc->channels, vcd_ch);
return SR_OK;
}
/**
* Construct the name of the nth sigrok channel for a VCD signal.
*
* Uses the VCD signal name for scalar types and single-bit signals.
* Uses "signal.idx" for multi-bit VCD signals without a range spec in
* their declaration. Uses "signal[idx]" when a range is known and was
* verified.
*
* @param[in] vcd_ch The VCD signal's description.
* @param[in] idx The sigrok channel's index within the VCD signal's group.
*
* @return An allocated text buffer which callers need to release, #NULL
* upon failure to create a sigrok channel name.
*/
static char *get_channel_name(struct vcd_channel *vcd_ch, size_t idx)
{
char *open_pos, *close_pos, *check_pos, *endptr;
gboolean has_brackets, has_range;
size_t upper, lower, tmp;
char *ch_name;
/* Handle simple scalar types, and single-bit logic first. */
if (vcd_ch->size <= 1)
return g_strdup(vcd_ch->name);
/*
* If not done before: Search for a matching pair of brackets in
* the right-most position at the very end of the string. Get the
* two colon separated numbers between the brackets, which are
* the range limits for array indices into the multi-bit signal.
* Grab the "base name" of the VCD signal.
*
* Notice that arrays can get nested. Earlier path components can
* be indexed as well, that's why we need the right-most range.
* This implementation does not handle bit vectors of size 1 here
* by explicit logic. The check for a [0:0] range would even fail.
* But the case of size 1 is handled above, and "happens to" give
* the expected result (just the VCD signal name).
*
* This implementation also deals with range limits in the reverse
* order, as well as ranges which are not 0-based (like "[4:7]").
*/
if (!vcd_ch->base_name) {
has_range = TRUE;
open_pos = strrchr(vcd_ch->name, '[');
close_pos = strrchr(vcd_ch->name, ']');
if (close_pos && close_pos[1])
close_pos = NULL;
has_brackets = open_pos && close_pos && close_pos > open_pos;
if (!has_brackets)
has_range = FALSE;
if (has_range) {
check_pos = &open_pos[1];
endptr = NULL;
upper = strtoul(check_pos, &endptr, 10);
if (!endptr || *endptr != ':')
has_range = FALSE;
}
if (has_range) {
check_pos = &endptr[1];
endptr = NULL;
lower = strtoul(check_pos, &endptr, 10);
if (!endptr || endptr != close_pos)
has_range = FALSE;
}
if (has_range && lower > upper) {
tmp = lower;
lower = upper;
upper = tmp;
}
if (has_range) {
if (lower >= upper)
has_range = FALSE;
if (upper + 1 - lower != vcd_ch->size)
has_range = FALSE;
}
if (has_range) {
/* Temporarily patch the VCD channel's name. */
*open_pos = '\0';
vcd_ch->base_name = g_strdup(vcd_ch->name);
*open_pos = '[';
vcd_ch->range_lower = lower;
vcd_ch->range_upper = upper;
}
}
has_range = vcd_ch->range_lower + vcd_ch->range_upper;
if (has_range && idx >= vcd_ch->size)
has_range = FALSE;
if (!has_range)
return g_strdup_printf("%s.%zu", vcd_ch->name, idx);
/*
* Create a sigrok channel name with just the bit's index in
* brackets. This avoids "name[7:0].3" results, instead results
* in "name[3]".
*/
ch_name = g_strdup_printf("%s[%zu]",
vcd_ch->base_name, vcd_ch->range_lower + idx);
return ch_name;
}
/*
* Create (analog or logic) sigrok channels for the VCD signals. Create
* multiple sigrok channels for vector input since sigrok has no concept
* of multi-bit signals. Create a channel group for the vector's bits
* though to reflect that they form a unit. This is beneficial when UIs
* support optional "collapsed" displays of channel groups (like
* "parallel bus, hex output").
*
* Defer channel creation until after completion of parsing the input
* file header. Make sure to create all logic channels first before the
* analog channels get created. This avoids issues with the mapping of
* channel indices to bitmap positions in the sample buffer.
*/
static void create_channels(const struct sr_input *in,
struct sr_dev_inst *sdi, enum sr_channeltype ch_type)
{
struct context *inc;
size_t ch_idx;
GSList *l;
struct vcd_channel *vcd_ch;
size_t size_idx;
char *ch_name;
struct sr_channel_group *cg;
struct sr_channel *ch;
inc = in->priv;
ch_idx = 0;
if (ch_type > SR_CHANNEL_LOGIC)
ch_idx += inc->logic_count;
if (ch_type > SR_CHANNEL_ANALOG)
ch_idx += inc->analog_count;
for (l = inc->channels; l; l = l->next) {
vcd_ch = l->data;
if (vcd_ch->type != ch_type)
continue;
cg = NULL;
if (vcd_ch->size != 1)
cg = sr_channel_group_new(sdi, vcd_ch->name, NULL);
for (size_idx = 0; size_idx < vcd_ch->size; size_idx++) {
ch_name = get_channel_name(vcd_ch, size_idx);
sr_dbg("sigrok channel idx %zu, name %s, type %s, en %d.",
ch_idx, ch_name,
ch_type == SR_CHANNEL_ANALOG ? "A" : "L", TRUE);
ch = sr_channel_new(sdi, ch_idx, ch_type, TRUE, ch_name);
g_free(ch_name);
ch_idx++;
if (cg)
cg->channels = g_slist_append(cg->channels, ch);
}
}
}
static void create_feeds(const struct sr_input *in)
{
struct context *inc;
GSList *l;
struct vcd_channel *vcd_ch;
size_t ch_idx;
struct sr_channel *ch;
inc = in->priv;
/* Create one feed for logic data. */
if (inc->logic_count) {
inc->unit_size = (inc->logic_count + 7) / 8;
inc->feed_logic = feed_queue_logic_alloc(in->sdi,
CHUNK_SIZE / inc->unit_size, inc->unit_size);
}
/* Create one feed per analog channel. */
for (l = inc->channels; l; l = l->next) {
vcd_ch = l->data;
if (vcd_ch->type != SR_CHANNEL_ANALOG)
continue;
ch_idx = vcd_ch->array_index;
ch_idx += inc->logic_count;
ch = g_slist_nth_data(in->sdi->channels, ch_idx);
vcd_ch->feed_analog = feed_queue_analog_alloc(in->sdi,
CHUNK_SIZE / sizeof(float),
vcd_ch->submit_digits, ch);
}
}
/*
* Keep track of a previously created channel list, in preparation of
* re-reading the input file. Gets called from reset()/cleanup() paths.
*/
static void keep_header_for_reread(const struct sr_input *in)
{
struct context *inc;
inc = in->priv;
g_slist_free_full(inc->prev.sr_groups, sr_channel_group_free_cb);
inc->prev.sr_groups = in->sdi->channel_groups;
in->sdi->channel_groups = NULL;
g_slist_free_full(inc->prev.sr_channels, sr_channel_free_cb);
inc->prev.sr_channels = in->sdi->channels;