+/*
+ * Fix up packet index entries for barectf's "event-before-packet" bug.
+ * Some buggy barectf tracer versions may emit events with a timestamp that is
+ * less than the timestamp_begin of the their packets.
+ *
+ * To fix up this erroneous data we do the following:
+ * 1. Starting at the second index entry, set the timestamp_begin of the
+ * current entry to the timestamp of the first event of the packet.
+ * 2. Set the previous entry's timestamp_end to the timestamp_begin of the
+ * current packet.
+ *
+ * Known buggy tracer versions:
+ * - before barectf 2.3.1
+ */
+static
+int fix_index_barectf_event_before_packet_bug(struct ctf_fs_trace *trace)
+{
+ int ret = 0;
+ guint ds_file_group_i;
+ GPtrArray *ds_file_groups = trace->ds_file_groups;
+ bt_logging_level log_level = trace->log_level;
+
+ for (ds_file_group_i = 0; ds_file_group_i < ds_file_groups->len;
+ ds_file_group_i++) {
+ guint entry_i;
+ struct ctf_clock_class *default_cc;
+ struct ctf_fs_ds_file_group *ds_file_group =
+ g_ptr_array_index(ds_file_groups, ds_file_group_i);
+
+ struct ctf_fs_ds_index *index = ds_file_group->index;
+
+ BT_ASSERT(index);
+ BT_ASSERT(index->entries);
+ BT_ASSERT(index->entries->len > 0);
+
+ BT_ASSERT(ds_file_group->sc->default_clock_class);
+ default_cc = ds_file_group->sc->default_clock_class;
+
+ /*
+ * 1. Iterate over the index, starting from the second entry
+ * (index = 1).
+ */
+ for (entry_i = 1; entry_i < index->entries->len;
+ entry_i++) {
+ struct ctf_fs_ds_index_entry *curr_entry, *prev_entry;
+ prev_entry = g_ptr_array_index(index->entries, entry_i - 1);
+ curr_entry = g_ptr_array_index(index->entries, entry_i);
+ /*
+ * 2. Set the current entry `begin` timestamp to the
+ * timestamp of the first event of the current packet.
+ */
+ ret = decode_packet_first_event_timestamp(trace, default_cc,
+ curr_entry, &curr_entry->timestamp_begin,
+ &curr_entry->timestamp_begin_ns);
+ if (ret) {
+ BT_LOGE_STR("Failed to decode first event's clock snapshot");
+ goto end;
+ }
+
+ /*
+ * 3. Set the previous entry `end` timestamp to the
+ * timestamp of the first event of the current packet.
+ */
+ prev_entry->timestamp_end = curr_entry->timestamp_begin;
+ prev_entry->timestamp_end_ns = curr_entry->timestamp_begin_ns;
+ }
+ }
+end:
+ return ret;
+}
+