Skip to content

Off-by-one error in examples and cli/main #7303

Description

@c14n

Throughout the examples we have code like this snippet from cli/main.c:

	if (git_libgit2_init() < 0) {
		cli_error("failed to initialize libgit2");
		exit(CLI_EXIT_GIT);
	}

This is subtly broken: As per the docs, git_libgit2_init() returns

the number of times the initialization has been called (including this one)

but we happily continue using the library if the function reports that the library has been initialized zero times. Normally, we wouldn't end up in this situation, but since git_libgit2_shutdown() will happily decrement init_count past zero, it's not impossible to end up in this trap due to programmer error.

I can think of two approaches to address this:

  1. Update cli and all the examples to use git_libgit2_init() <= 0.
  2. Never return 0 from git_runtime_init().

The first approach does not fix any downstream code that is currently broken in this way. It also violates the usual convention that zero means success, which probably also plays a part in why this wasn't spotted earlier.

The second approach can be accomplished by never allowing init_count to go negative in the first place. So something along the lines of !7299 would actually fix this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions