Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Naios opened this issue Mar 23, 2024 · 0 comments · May be fixed by #290

Comments

@Naios
Copy link

Naios commented Mar 23, 2024

0066e60

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 added a commit to Naios/inja that referenced this issue Mar 27, 2024
@Naios Naios changed the title Inja invalid memory access in loops due to missing pointer instability when using INJA_DATA_TYPE=nlohmann::ordered_json Inja invalid memory access in loops due to missing pointer stability when using INJA_DATA_TYPE=nlohmann::ordered_json Mar 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant