Re: [PATCH v13 1/3] rust: io: add resource abstraction
From: Alice Ryhl
Date: Wed Jul 16 2025 - 13:05:03 EST
On Wed, Jul 16, 2025 at 6:53 PM Daniel Almeida
<daniel.almeida@xxxxxxxxxxxxx> wrote:
>
> Hi Alice,
>
> >
> >> + let inner = self.0.get();
> >> + // SAFETY: safe as per the invariants of `Resource`.
> >> + unsafe { (*inner).start }
> >> + }
> >> +
> >> + /// Returns the name of the resource.
> >> + pub fn name(&self) -> &'static CStr {
> >> + let inner = self.0.get();
> >> + // SAFETY: safe as per the invariants of `Resource`
> >> + unsafe { CStr::from_char_ptr((*inner).name) }
> >
> > This is 'static? I would like this safety comment to explicitly say that
> > the string always lives forever no matter what resource you call this
> > on.
> >
> > Alice
> >
>
> Actually, we have a bit of a problem here.
>
> First, there appears to be no guarantee that a `Resource` has a valid name.
>
> In fact:
>
> #define DEFINE_RES_NAMED(_start, _size, _name, _flags) \
> DEFINE_RES_NAMED_DESC(_start, _size, _name, _flags, IORES_DESC_NONE)
> #define DEFINE_RES(_start, _size, _flags) \
> DEFINE_RES_NAMED(_start, _size, NULL, _flags)
>
> #define DEFINE_RES_IO_NAMED(_start, _size, _name) \
> DEFINE_RES_NAMED((_start), (_size), (_name), IORESOURCE_IO)
> #define DEFINE_RES_IO(_start, _size) \
> DEFINE_RES_IO_NAMED((_start), (_size), NULL)
>
> The non _NAMED version of these macros will assign a NULL pointer, so we can't
> derive a CStr from that at all.
>
> On top of that, although some call sites do use static names, i.e.:
>
> struct resource ioport_resource = {
> .name = "PCI IO",
> .start = 0,
> .end = IO_SPACE_LIMIT,
> .flags = IORESOURCE_IO,
> };
> EXPORT_SYMBOL(ioport_resource);
>
> struct resource iomem_resource = {
> .name = "PCI mem",
> .start = 0,
> .end = -1,
> .flags = IORESOURCE_MEM,
> };
> EXPORT_SYMBOL(iomem_resource);
>
> static struct resource busn_resource = {
> .name = "PCI busn",
> .start = 0,
> .end = 255,
> .flags = IORESOURCE_BUS,
> };
>
> Some appear to use other, smaller lifetimes, like the one below:
>
> struct pnp_resource *pnp_add_resource(struct pnp_dev *dev,
> struct resource *res)
> {
> struct pnp_resource *pnp_res;
>
> pnp_res = pnp_new_resource(dev);
> if (!pnp_res) {
> dev_err(&dev->dev, "can't add resource %pR\n", res);
> return NULL;
> }
>
> pnp_res->res = *res;
> pnp_res->res.name = dev->name;
>
>
> I guess the easiest solution is to drop 'static in order to account for the
> above, and change the signature to return Option<&CStr> instead.
Using Option<&CStr> sounds good to me.