"node-addon-api"中的某些 API 是否存在"undefined behavior"问题?



<napi.h>中,类PropertyDescriptor中有一些静态方法Accessor的重载声明。

其中一个过载声明在这里:

template <typename Getter>
static PropertyDescriptor Accessor(Napi::Env env,
Napi::Object object,
const std::string& utf8name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);

该声明希望引用const std::string

该声明的定义在<napi inl.h>:

template <typename Getter>
inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
Napi::Object object,
const std::string& utf8name,
Getter getter,
napi_property_attributes attributes,
void* data) {
return Accessor(env, object, utf8name.c_str(), getter, attributes, data);
}

正如您所看到的,该实现采用传递的std::string.c_str(),因为该实现实际上使用了另一个需要const char*的重载。

使用的过载也在<napi-inl.h>:中

template <typename Getter>
inline PropertyDescriptor
PropertyDescriptor::Accessor(Napi::Env env,
Napi::Object object,
const char* utf8name,
Getter getter,
napi_property_attributes attributes,
void* data) {
using CbData = details::CallbackData<Getter, Napi::Value>;
auto callbackData = new CbData({ getter, data });
napi_status status = AttachData(env, object, callbackData);
if (status != napi_ok) {
delete callbackData;
NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
}
return PropertyDescriptor({
utf8name,
nullptr,
nullptr,
CbData::Wrapper,
nullptr,
nullptr,
attributes,
callbackData
});
}

该实现使用Node-API,因为node-addon-api只是Node-API周围的C++包装器。事实是,从.c_str()获得的const char* utf8name按原样传递给构造函数,并存储在私有成员napi_property_descriptor _desc;

结论:每次使用Napi::PropertyDescriptor::Accessor传递std::字符串,然后将PD存储在向量中,或者只是在PD仍在的情况下使字符串超出范围,都会触发未定义的行为!

示例:

Napi::Object TheNewObject = Napi::Object::New(env);
std::vector<Napi::PropertyDescriptor> vProps;
for (size_t index = 0; index < 2; ++index ) {
std::string strName("MyName_");
strName += std::to_string(index);
auto PD = Napi::PropertyDescriptor::Accessor(env, TheNewObject, strName, Caller);
vProps.push_back(PD);
} 

12天前,我在这里开了一期,但没有成功。

编辑:在阅读评论后,我应该补充一下:

napi_property_descriptor是一个简单的C结构
  • 该结构体的地址稍后将传递给Node-APInapi_define_properties
  • PropertyDescriptor的当前实现确实存在问题。看见https://github.com/nodejs/node-addon-api/issues/1127#issuecomment-1036394322

    很高兴我没有完全神志不清。

    最新更新