inja icon indicating copy to clipboard operation
inja copied to clipboard

Inja invalid memory access in loops due to missing pointer stability when using `INJA_DATA_TYPE=nlohmann::ordered_json`

Open Naios opened this issue 1 year ago • 0 comments

0066e6049e486fa4bbc52c062a22efb594f1cf05

Thank you for your awesome library, it works very well.

I have been trying to process an ordered json that I have generated with nlohmann::ordered_json. Therefore, I have defined INJA_DATA_TYPE as nlohmann::ordered_json.

It seems that the code that processes the loop object iteration has issues with missing pointer stability in this case:

    if (!current_loop_data->empty()) {
      (*current_loop_data)["parent"] = std::move(*current_loop_data);
    }

    size_t index = 0;
    (*current_loop_data)["is_first"] = true;
    (*current_loop_data)["is_last"] = (result->size() <= 1);
    for (auto it = result->begin(); it != result->end(); ++it) {
      additional_data[static_cast<std::string>(node.key)] = it.key();
      additional_data[static_cast<std::string>(node.value)] = it.value();

      (*current_loop_data)["index"] = index;
      // ^^^^ first invalid access here
      (*current_loop_data)["index1"] = index + 1;
      if (index == 1) {
        (*current_loop_data)["is_first"] = false;
      }
      if (index == result->size() - 1) {
        (*current_loop_data)["is_last"] = true;
      }

It seems current_loop_data points to an invalid memory location in this case if the elements in the ordered map gets shifted around or are reallocated. While this seems to work with the unordered nlohmann::json, it breaks when using nlohmann::ordered_json. Also it seems that nlohmann::json does not document to provide stable pointers either, so maybe your library currently relies on this behaviour, without nlohmann::json providing official support for it.


This can be reproduced with:

Define: INJA_DATA_TYPE=nlohmann::ordered_json

{
  "objects": {
    "a": { },
    "b": { }
  }
}
{% for object_name, object in objects %}
- {{object_name}}
{% endfor %}

Thank you in advance.

Naios avatar Mar 23 '24 23:03 Naios