Skip to content

Core: Calling op_set_option even if no default context is set - #942

Closed
harbulot wants to merge 1 commit into
libusb:masterfrom
harbulot:android_set_option_weak_authority
Closed

harbulot wants to merge 1 commit into
libusb:masterfrom
harbulot:android_set_option_weak_authority

Conversation

@harbulot

Copy link
Copy Markdown
Contributor

Following the dicussion in #830, it appears that:

  • Calling libusb_init(NULL) on Android doesn't work.

  • We should call libusb_set_option(NULL, LIBUSB_OPTION_WEAK_AUTHORITY) before calling libusb_init(&ctx).

  • LIBUSB_OPTION_WEAK_AUTHORITY is effectively used in linux_usbfs.c, in op_set_option, itself called from core.c via usbi_backend.set_option.

However, following the changes in commit a524555, it seems that usbi_backend.set_option(...) is never called if no default context has been set up. In the following code fragment (line 2207):

	ctx = usbi_get_context(ctx);
	if (NULL == ctx) {
		return LIBUSB_SUCCESS;
	}

	switch (option) {
	case LIBUSB_OPTION_LOG_LEVEL:
#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
		if (!ctx->debug_fixed)
			ctx->debug = (enum libusb_log_level)arg;
#endif
		break;

		/* Handle all backend-specific options here */
	case LIBUSB_OPTION_USE_USBDK:
	case LIBUSB_OPTION_WEAK_AUTHORITY:
		if (usbi_backend.set_option)
			return usbi_backend.set_option(ctx, option, ap);

		return LIBUSB_ERROR_NOT_SUPPORTED;
		break;

If the default context (usbi_default_context) is NULL and we call libusb_set_option with a NULL context, then usbi_get_context(ctx) returns NULL:

static inline struct libusb_context *usbi_get_context(struct libusb_context *ctx)
{
	return ctx ? ctx : usbi_default_context;
}

As a result, in this case, we return from libusb_set_option at line 2209 (if (NULL == ctx) { return LIBUSB_SUCCESS; }), so usbi_backend.set_option is never called, and weak_authority in linux_usbfs.c is never set to 1.

Moving if (NULL == ctx) { return LIBUSB_SUCCESS; } after that switch statement seems to fix the problem for LIBUSB_OPTION_WEAK_AUTHORITY.

That said, I'm not sure how it affects LIBUSB_OPTION_USE_USBDK, which is currently treated in the same case as LIBUSB_OPTION_WEAK_AUTHORITY in the switch statement. Although op_set_option doesn't make use of ctx in linux_usbfs.c when it deals with LIBUSB_OPTION_WEAK_AUTHORITY, it seems that windows_set_option in windows_common.c makes use of it.

I don't know enough about the implementation details of libusb, but maybe LIBUSB_OPTION_USE_USBDK and LIBUSB_OPTION_WEAK_AUTHORITY should be treated separately, perhaps like this:

	case LIBUSB_OPTION_USE_USBDK:
		if (ctx && usbi_backend.set_option)
			return usbi_backend.set_option(ctx, option, ap);
		return LIBUSB_ERROR_NOT_SUPPORTED;
		
	case LIBUSB_OPTION_WEAK_AUTHORITY:
		if (usbi_backend.set_option)
			return usbi_backend.set_option(ctx, option, ap);
		return LIBUSB_ERROR_NOT_SUPPORTED;

@xloem

xloem commented Jun 27, 2021 •

Copy link
Copy Markdown
Contributor

Since the default context is made in libusb_init, commit a524555 broke WEAK_AUTHORITY. It looks like the intention of the commit is to move options like WEAK_AUTHORITY and weak_authority into default_context_options so that they are properly protected from use across threads by default_context_lock. But a stopgap measure is needed to get WEAK_AUTHORITY working again until that change is implemented.

The return block pasted to the end of the function in this PR is redundant with the return statement following it; I might comment it out instead of moving it, with a link to for example this PR in the comment, not sure.

#935 also works with this option.

@harbulot

Copy link
Copy Markdown
Contributor Author

Thank you for your feedback @xloem (and you're right the return block was redundant, sorry).

I've removed it and made the modification so that the behaviour with LIBUSB_OPTION_USE_USBDK shouldn't be affected. With a NULL context, it will still return LIBUSB_SUCCESS without doing anything. (It's the same behaviour as after the a524555 commit, but I don't think it would necessarily have returned LIBUSB_SUCCESS with a NULL context before that patch. I'm not sure what the best thing to do here is.)

Renaming WEAK_AUTHORITY to NO_DEVICE_DISCOVERY should be relatively straightforward. (Please let me know if you'd like me to update this PR when needed.)

@xloem

xloem commented Jul 4, 2021 •

Copy link
Copy Markdown
Contributor

@harbulot @hjelmn I took a different approach to this problem (both approaches actually address different option uses, merge without conflict, and are merged together in my big pr) at master...xloem:weak-authority . The weak_authority variable holds the same information as the new is_set struct member, so I removed the former and replaced it. What do you think of this approach? I'm not set up to test weak_authority so it may have a bug.

@xloem xloem mentioned this pull request Jul 5, 2021
6 of 15 tasks
@mcuee mcuee added the linux label Jul 5, 2021
mcuee referenced this pull request Jul 5, 2021
This commit updates libusb_set_option to save the options if setting them on the default
context. This ensures the options 1) can be set before libusb_init(NULL, ...), and 2)
are honored even if the default context is destroyed and re-created.

Signed-off-by: Nathan Hjelm <[email protected]>
@mcuee mcuee mentioned this pull request Jul 5, 2021
@mcuee

mcuee commented Jul 9, 2021

Copy link
Copy Markdown
Member

@harbulot @xloem #935 has been merged. It this still required?

@mcuee

mcuee commented Jul 21, 2021

Copy link
Copy Markdown
Member

Ping @harbulot

@mcuee

mcuee commented Jul 21, 2021

Copy link
Copy Markdown
Member

Ping @xloem

@xloem

xloem commented Jul 21, 2021 •

Copy link
Copy Markdown
Contributor

As far as I can tell, yes it is. It looks like the control flow change still prevents no_enumeration from being set.

edit: to add more, I could update #874 to not need this PR, since it now checks the default context options directly. But, at present, android support is broken in libusb HEAD, and this PR #942 should fix that. [i have rebased this PR in the next comment]

@xloem

xloem commented Jul 21, 2021

Copy link
Copy Markdown
Contributor

harbulot#1 , or as a rebase at xloem@9a08754

@hjelmn

hjelmn commented Jul 22, 2021

Copy link
Copy Markdown
Member

usbi.set_backend should be getting called when a context is created. Doesn't matter to me when it happens but that was the idea. Sounds like that did not work as intended.

I will take a look at this tomorrow.

@hjelmn

hjelmn commented Jul 22, 2021

Copy link
Copy Markdown
Member

I see the issue. The backend set option was getting called after the backend init. That is too late for this use case. I can move the set to before the backend init.

@xloem

xloem commented Jul 22, 2021 •

Copy link
Copy Markdown
Contributor

@hjelmn it sounds like you view the issue in terms of the call order to set_backend ... I'm not too familiar with the core code, but this handles a legacy use of set_option before usb_init, that was broken with the redesign. OPTION_NO_DEVICE_DISCOVERY is used before there is any context object.

I kind of expect that anybody who's worked with the code would want to migrate off of that, but it would mean changing the init() flow around a lot in linux_usbfs, or providing for passing options to usb_init.

Let us know when/if you have a change in place.

hjelmn added a commit that referenced this pull request Jul 27, 2021
This commit restores the previous behavior with regards to setting some backend options and
restores the ability to set default context options before libusb_init. None of the backends
use anything set in init in their set_option function so this should be safe with all
backends and options.

References #942

Signed-off-by: Nathan Hjelm <[email protected]>
@hjelmn

hjelmn commented Aug 8, 2021

Copy link
Copy Markdown
Member

I submitted my fix. Can you verify that it addresses the issue?

@mcuee

mcuee commented Aug 10, 2021

Copy link
Copy Markdown
Member

Ping @xloem @harbulot

@xloem

xloem commented Aug 10, 2021

Copy link
Copy Markdown
Contributor

@harbulot are you available to test the alternative fix for this issue you raised?

What we need here is to test a WEAK_AUTHORITY app using the latest code from trunk, which has unfortunately changed. I may be able to set up for android again and build a new test app for this if nobody's available with an old one of their own.

@harbulot
harbulot force-pushed the android_set_option_weak_authority branch from b025282 to d04b8c8 Compare August 10, 2021 19:14
@harbulot

Copy link
Copy Markdown
Contributor Author

Apologies for the delay. I've just tried and rebased/altered the patch I'd initially submitted onto the current master revision (1a90627).

This PR should be updated now, it's very short. Essentially, it was still returning too early if usbi_get_context(ctx) returned a NULL context, which is what happens for the default context (as far as I understand). libusb_init was still crashing on Android without this patch, but it seems to work fine with this small change.

--- a/libusb/core.c
+++ b/libusb/core.c
@@ -2208,14 +2208,11 @@ int API_EXPORTED libusb_set_option(libusb_context *ctx,
        }

        ctx = usbi_get_context(ctx);
-       if (NULL == ctx) {
-               return LIBUSB_SUCCESS;
-       }

        switch (option) {
        case LIBUSB_OPTION_LOG_LEVEL:
 #if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
-               if (!ctx->debug_fixed)
+               if (ctx && !ctx->debug_fixed)
                        ctx->debug = (enum libusb_log_level)arg;
 #endif
                break;

I can also confirms it also works with the new LIBUSB_OPTION_NO_DEVICE_DISCOVERY option.

@xloem

xloem commented Aug 10, 2021 •

Copy link
Copy Markdown
Contributor

It looks like there's still some bug. I think the intended behavior of hjelmn's change was to make the needed set_option call again in libusb_init after the ctx object is set. Now with this PR there are two solutions, which is not harmful and fixes the serious issue, but is a little disordered. Maybe the set_option call is out of order in hjelmn's fix or some other issue with the details of the execution flow.

@hjelmn

hjelmn commented Aug 12, 2021 •

Copy link
Copy Markdown
Member

@harbulot Can you try with just the head (not with this patch)? It should just work as we are caching the options set before libusb_init and applying them before the backend is initialized. That should catch this use case. If that still crashes please post a debug log and I can take a look.

@harbulot

Copy link
Copy Markdown
Contributor Author

Thanks @hjelmn, I think I've found the cause of the problem. I'm not using the default (NULL) context, but I'm trying to get a non-default context from libusb_init (i.e. using libusb_init(&ctx) and not libusb_init(NULL)).

Here is the code I'm using:

    int r;
    libusb_context *ctx = NULL;

    r = libusb_set_option(NULL, LIBUSB_OPTION_NO_DEVICE_DISCOVERY);
    __android_log_print(ANDROID_LOG_DEBUG, TAG,
                        "libusb_set_option LIBUSB_OPTION_NO_DEVICE_DISCOVERY: %d", r);

    r = libusb_init(&ctx);
    __android_log_print(ANDROID_LOG_DEBUG, TAG, "libusb_init(&ctx): %d", r);
    if (r < 0) {
        return r;
    }

With the latest commit (1a90627), I get this trace (and the app crashes):

D/LibUsbAndroid942: Using file descriptor: 80
D/LibUsbAndroid942: libusb_set_option LIBUSB_OPTION_LOG_LEVEL: 0
D/LibUsbAndroid942: libusb_set_option LIBUSB_OPTION_WEAK_AUTHORITY: 0
D/libusb: [timestamp] [threadID] facility level [function call] <message>
D/libusb: --------------------------------------------------------------------------------
D/libusb: [ 0.000024] [00002ca2] libusb: debug [libusb_init] libusb v1.0.24.11650
D/libusb: [ 0.000091] [00002ca2] libusb: debug [usbi_add_event_source] add fd 90 events 1
D/libusb: [ 0.000164] [00002ca2] libusb: debug [get_kernel_version] reported kernel version is 4.9.190
D/libusb: [ 0.000293] [00002ca2] libusb: debug [op_init] found usbfs at /dev/bus/usb
D/libusb: [ 0.000320] [00002ca2] libusb: debug [op_init] max iso packet length is (likely) 49152 bytes
D/libusb: [ 0.000364] [00002ca2] libusb: debug [op_init] sysfs is available
E/libusb: [ 0.000441] [00002ca2] libusb: error [sysfs_get_device_list] opendir devices failed, errno=13
W/androidissue942: type=1400 audit(0.0:2861): avc: denied { read } for name="usb" dev="tmpfs" ino=13344 scontext=u:r:untrusted_app:s0:c152,c256,c512,c768 tcontext=u:object_r:usb_device:s0 tclass=dir permissive=0

With the patch in this PR, the app works and I get this trace:

D/LibUsbAndroid942: Using file descriptor: 85
D/LibUsbAndroid942: libusb_set_option LIBUSB_OPTION_LOG_LEVEL: 0
D/libusb: [timestamp] [threadID] facility level [function call] <message>
D/libusb: --------------------------------------------------------------------------------
D/libusb: [4277.415912] [00002d42] libusb: debug [op_set_option] no enumeration will be performed
D/LibUsbAndroid942: libusb_set_option LIBUSB_OPTION_WEAK_AUTHORITY: 0
D/libusb: [ 0.000002] [00002d42] libusb: debug [libusb_init] libusb v1.0.24.11650
D/libusb: [ 0.000086] [00002d42] libusb: debug [usbi_add_event_source] add fd 92 events 1
D/libusb: [ 0.000173] [00002d42] libusb: debug [get_kernel_version] reported kernel version is 4.9.190
D/libusb: [ 0.000310] [00002d42] libusb: debug [op_init] found usbfs at /dev/bus/usb
D/libusb: [ 0.000332] [00002d42] libusb: debug [op_init] max iso packet length is (likely) 49152 bytes
D/libusb: [ 0.000375] [00002d42] libusb: debug [op_init] sysfs is available
D/LibUsbAndroid942: libusb_init(&ctx): 0

(That was because no_enumeration was not set to 1 in the case where the app crashes.)

When I change libusb_init(&ctx) to libusb_init(NULL), it seems to work too, even without the patch in this PR.

    int r;

    r = libusb_set_option(NULL, LIBUSB_OPTION_NO_DEVICE_DISCOVERY);
    __android_log_print(ANDROID_LOG_DEBUG, TAG,
                        "libusb_set_option LIBUSB_OPTION_NO_DEVICE_DISCOVERY: %d", r);

    r = libusb_init(NULL);
    __android_log_print(ANDROID_LOG_DEBUG, TAG, "libusb_init(NULL): %d", r);
    if (r < 0) {
        return r;
    }

Having looked a bit further into the code, it makes sense, since libusb_set_option (as called from within libusb_init) is only ever called when ctx is NULL:

	/* default context should be initialized before calling usbi_dbg */
	if (!ctx) {
		usbi_default_context = _ctx;
		default_context_refcnt = 1;
		usbi_dbg(usbi_default_context, "created default context");

		for (enum libusb_option option = 0 ; option < LIBUSB_OPTION_MAX ; option++) {
			if (LIBUSB_OPTION_LOG_LEVEL == option || !default_context_options[option].is_set) {
				continue;
			}
			r = libusb_set_option(_ctx, option);
			if (LIBUSB_SUCCESS != r)
				goto err_free_ctx;
		}
	}

I can't find where I've read it, but my understanding was that it was recommended to use a non-default context for Android apps (i.e. initialise a context with libusb_init(&ctx) and not rely on a NULL context). I'm not sure how important this is in general, though.

I think the main problem in the latest master revision is that there appears to be some ambiguity about the role of default_context_options. It seems it can refer to:

  • the options of the default context (in which case there's probably no reason to have default_context_options at all, since libusb_set_option would work on usbi_default_context after it's been initialised), or
  • the default options for new contexts (not initialised yet), in which case those options should probably be set whether or not ctx (in libusb_init) is NULL.

As it stands, it looks like it may be a mix of both: default options that can be set before initialising the default context (and only the default context). What is it actually intended to be?

@hjelmn

hjelmn commented Aug 12, 2021

Copy link
Copy Markdown
Member

Ah, I see. Makes sense. I see no reason to apply the default context options set before libusb_init(NULL) to any new context.

@harbulot

Copy link
Copy Markdown
Contributor Author

I see no reason to apply the default context options set before libusb_init(NULL) to any new context.

Sorry, not sure I understand what you mean.

Are you saying we shouldn't be able to use LIBUSB_OPTION_NO_DEVICE_DISCOVERY (or other options that need to be set before calling libusb_init) on contexts other than the default context?

Should LIBUSB_OPTION_NO_DEVICE_DISCOVERY be limited to libusb_init(NULL) and not be expected to work with libusb_init(&ctx)?

@hjelmn

hjelmn commented Aug 12, 2021

Copy link
Copy Markdown
Member

@harbulot I mean if an option is set on the NULL context before any call to libusb_init it makes sense to apply it to all the following libusb_init() calls regardless of context. Instead of thinking of them as default options instead of default context options.

@harbulot
harbulot force-pushed the android_set_option_weak_authority branch from d04b8c8 to 0b1b2ba Compare August 12, 2021 19:33
@harbulot

Copy link
Copy Markdown
Contributor Author

Thanks @hjelmn, I've just updated the PR.

Essentially, in libusb_init, if it's a new context (i.e. ctx is not NULL) or if the default context (usbi_default_context) has not been configured yet, then we apply all the options (just moving the options loop you had before).

The only reason I've put this condition is to avoid setting the options again if the default context had already been initialised.

Does it make sense?

I've tried with my test case on Android, and it works.

@mcuee mcuee changed the title Calling op_set_option even if no default context is set Android: Calling op_set_option even if no default context is set Sep 24, 2021
@xloem

xloem commented Sep 24, 2021

Copy link
Copy Markdown
Contributor

@hjelmn would it be helpful here if somebody wrote up a dummy backend that can reproduce the issue without running on android?

@harbulot

Copy link
Copy Markdown
Contributor Author

@mcuee Just to clarify, it seems to be an issue that affects particularly Android, because that's where the usage flow requires options to be configured before initialising a context, but that would generally apply to other platforms too where default context options have to be set, so it's not really Android-specific as such.
At the moment (without this patch), you just can't the default context options before creating a context. (I realise the branch name I'd initially given contains the word "android", but that's only because that's what I was looking into at the time.)

@tormodvolden

Copy link
Copy Markdown
Contributor

In that case, feel free to change your merge request title to not include "Android".

@mcuee mcuee added the core Related to common codes label Sep 29, 2021
@mcuee mcuee changed the title Android: Calling op_set_option even if no default context is set Core: Calling op_set_option even if no default context is set Sep 29, 2021
@tormodvolden

tormodvolden commented Oct 2, 2021 •

Copy link
Copy Markdown
Contributor

Would this be fine to add to the libusb_set_option documentation?

+ * If the context ctx is NULL, the option will be added to a list of default
+ * options that will be applied to all subsequently created contexts.

I use the word "created" because it is consistent with the libusb_init() and "Contexts" documentation. In the discussion above it is often said "initialized" which means the same. I mean, there is no "default context" existing before the first libusb_init(NULL).

Now, if you want to have one context where you want to skip enumeration (because you use libusb_wrap_sys() anyway) and another context with enumeration, you will have to initialize the latter first, then set LIBUSB_OPTION_NO_DEVICE_DISCOVERY and initialize the former. If these are in independent plug-ins (like the example in the Contexts documentation) this is not ideal. I guess we could make libusb_set_option(NULL, LIBUSB_OPTION_NO_DEVICE_DISCOVERY, 0) work to turn it off, or we need something more sophisticated to manipulate the default options in general. If we were to start from scratch, I think there should have been a flag option argument to libusb_init(), and the options being bit masks...

@xloem

xloem commented Oct 17, 2021

Copy link
Copy Markdown
Contributor

Just a note that any of the various forms of this PR appear fine to me to merge into a release. They are small changes that prevent a regression and can be reverted later if the options system is unified or improved further.

@xloem

xloem commented Nov 1, 2021

Copy link
Copy Markdown
Contributor

@hjelmn I pinged you late september and it's now november; is it all right if something is merged to resolve this regression?

tormodvolden added a commit that referenced this pull request Nov 1, 2021
@tormodvolden

Copy link
Copy Markdown
Contributor

I reviewed this again closely and it seems fine. I took the liberty to adjust some comments and wrote a proper commit message.

Comment thread libusb/core.c Resolved
tormodvolden added a commit that referenced this pull request Nov 9, 2021
After commit f7084fe the if clause would always be true, so remove it.

Thanks to "xloem" for reporting.

References #942

Signed-off-by: Tormod Volden <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

android core Related to common codes linux

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants