On Windows gio runs a thread to update appinfo at startup.
If someone unloads gio (this happens when a dynamic gio module gets
unloaded by a program that doesn't use gio itself), there doesn't seem
to be a way to detect that until gio is already gone, and as soon as
gio is gone, the thread crashes, since it tries to execute instructions
that are no longer there.
Holding an extra reference to gio DLL fixes this, but it also prevents
gio from being unloaded, and there's no "weak references" for DLLs.
So we just pin gio and acknowledge that it will never be unloaded.
Fixes#2300Fixes#2359
1) Check that schedule_call_in_idle code branch of gdbusnamewatching.c
is working to call vanished handler in the thread which had watched the name
2) Check cancellation of vanished handler if the name is unwatched before
vanished callback is dispatched.
Closes#2011
Signed-off-by: Frederic Martinsons <frederic.martinsons@sigfox.com>
After the recent reworking of this code it was possible for `g_close()`
to be called on `fd == -1`, which is invalid. It would have reported an
error, were errors not ignored. So it was harmless, but still best to
fix.
Simplify the error handling by combining both error labels and checking
the state of `fd` dynamically.
Coverity CID: #1450834
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
The variable `gconstructor_code` (which is what’s defined by
`gconstructor_as_data_h`) is not used at all inside
`glib-compile-schemas`.
This looks like a copy/paste error from the build definition for
`glib-compile-resources` below, which does need it.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
In the 2.68 cycle we’d added 3 new enumerator elements. Due to the
preceding commit, they can now be annotated with
`GLIB_AVAILABLE_ENUMERATOR_IN_2_68`, which will make it a bit easier for
third party projects to notice when they’re using these symbols without
having bumped their GLib dependency.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2327
`""` is not a valid path (`stat()` on it returns `ENOENT`). Previously,
a full `GLocalFile` was being created, which ended up resolving to
`$CWD`, through path canonicalisation. That isn’t right.
Fix it by creating a `GDummyFile` instead, and adding a unit test.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2328
Calling `dlopen()` with `libutil.so` makes the installed tests depend on
having glibc's development files installed. To avoid this, we can work
out the runtime library name at build time and `dlopen` that instead.
This approach is [taken from libfprint][1], thanks to Marco Trevisan.
[1]: f401f399a8
`ENXIO` can be returned from `open(2)` for special files (FIFOs, device
files and domain sockets) which are not backed by anything.
This fixes the error returned by `g_file_replace()` when trying to
replace such a file, so that it now matches the documentation.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
These test all the functionality and combinations of flags I can think
of. They do not cover dynamic behaviour (for example, what would happen
if the source file is deleted by another process part-way through a call
to `g_file_replace()`).
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
The `G_FILE_CREATE_REPLACE_DESTINATION` flag is equivalent to unlinking
the destination file and re-creating it from scratch. That did
previously work, but in the process the code would call `open(O_CREAT)`
on the file. If the file was a dangling symlink, this would create the
destination file (empty). That’s not an intended side-effect, and has
security implications if the symlink is controlled by a lower-privileged
process.
Fix that by not opening the destination file if it’s a symlink, and
adjusting the rest of the code to cope with
- the fact that `fd == -1` is not an error iff `is_symlink` is true,
- and that `original_stat` will contain the `lstat()` results for the
symlink now, rather than the `stat()` results for its target (again,
iff `is_symlink` is true).
This means that the target of the dangling symlink is no longer created,
which was the bug. The symlink itself continues to be replaced (as
before) with the new file — this is the intended behaviour of
`g_file_replace()`.
The behaviour for non-symlink cases, or cases where the symlink was not
dangling, should be unchanged.
Includes a unit test.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2325
Since a following commit is going to add a new test which references
Gitlab, so it’s best to move the URI bases inside the test cases.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
When GLib code is checked out with Windows line endings (happens on Windows),
data-to-c.py embedded that line endings into generated string literal. And
then they translated to double newlines in glib-compile-resources output.
clang-cl failed to compile such files because of empty lines in the middle of
multiline macros:
#define G_MSVC_CTOR(_func,_sym_prefix) \
static void _func(void); \
To fix the issue, enable 'universal newlines' mode when reading the input in
data-to-c.py - translate both '\n' and '\r\n' to '\n'.
Fixes https://gitlab.gnome.org/GNOME/glib/-/issues/2340
This will require distributions to ensure they pass
`--localstatedir=/var` correctly to Meson, but they should be doing that
already.
See https://mesonbuild.com/Builtin-options.html#directories for details
about how Meson treats `localstatedir` differently from most other `dir`
variables.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
It’s unlikely that the machine ID will be invalid (it’s system
configuration), but it would be helpful to not propagate invalid IDs
further, since a lot of things rely on it.
It’s not easy to test this (it requires factoring out the code so it can
be used from a test program, or allowing it to load a machine ID from a
custom path), so I haven’t added unit tests. I’ve tested manually by
overriding the loaded machine ID.
Coverity CID: #1430944
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
For non-Linux UNIX systems, the label 'close_libutil:' in
'test_pollable_unix_pty()' will have no statement that goes with that
label. Just do a 'return' on non-Linux UNIX systems.
File monitor creation may fail. We should check for this, rather than
ignoring it and then spewing criticals upon improperly assuming that we
have a valid GFileMonitor rather than NULL.
In practice, creating the GFileMonitors here fail when opening a large
number of tabs in Epiphany. I'm still investigating to see why, but it
doesn't matter for the purposes of this commit.
Expand an existing unit test to check that the target FD of a
`g_subprocess_launcher_take_fd()` call doesn’t get closed when
`g_subprocess_launcher_close()` is called. Only the source FD should be
closed by the parent process.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2332
This is a regression introduced in commit 67a589e505. Previously, the
source/target FD pairs were stored in `needdup_fd_assignments`, in
consecutive entries, so source FDs had even indices and target FDs had
odd indices.
I didn’t notice that the array index was being incremented by 2 when
closing FDs, when porting from the old code. So previously the code was
only closing the source FDs; after the port, it was closing source and
target FDs.
That’s incorrect, as the target FDs are just integers in the parent
process. It’s only in the child process where they are actually FDs —
and `g_subprocess_launcher_close()` is never called in the child
process.
This resulted in some strange misbehaviours in any process which used
`g_subprocess_launcher_take_fd()` with target FDs which could have
possibly aliased with other FDs in the parent process (and which weren’t
equal to their mapped source FDs).
Thanks to Olivier Fourdan for the detailed bug report.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2332
This was correctly annotated for proper return values but in case of out
parameters it was only annotated as (optional) and not additionally as
(nullable).
This improves performance by eliminating the use of a
`GSpawnChildSetupFunc` in the common case (since that setup code has now
moved into `g_spawn*()` itself), and enables the use of the fix to avoid
the child error reporting FD being overwritten by target FD mappings,
introduced via `g_spawn_async_with_pipes_and_fds()`.
It reworks how the source/target FD mapping is stored within
`GSubprocessLauncher` to match what `g_spawn*()` uses. The two
approaches are equivalent.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2097
gio/gmemoryoutputstream.c: In function ‘g_memory_output_stream_seek’:
gio/gmemoryoutputstream.c:792:44: error: comparison of integer expressions of different signedness: ‘goffset’ {aka ‘long int’} and ‘gsize’ {aka ‘long unsigned int’}
792 | if (priv->realloc_fn == NULL && absolute > priv->len)
| ^
gio/gdummyfile.c: In function ‘unescape_string’:
gio/gdummyfile.c:485:32: error: comparison of integer expressions of different signedness: ‘long int’ and ‘size_t’ {aka ‘long unsigned int’}
485 | g_warn_if_fail (out - result <= strlen (escaped_string));
| ^~
gio/gapplication-tool.c: In function ‘app_help’:
glib/gmacros.h:806:26: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘size_t’ {aka ‘long unsigned int’}
gio/gapplication-tool.c:121:26: note: in expansion of macro ‘MAX’
121 | maxwidth = MAX(maxwidth, strlen (_(substvars[i].var)));
| ^~~
gio/gapplication-tool.c: In function ‘app_help’:
glib/gmacros.h:806:26: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘size_t’ {aka ‘long unsigned int’}
gio/gapplication-tool.c:140:20: note: in expansion of macro ‘MAX’
140 | maxwidth = MAX(maxwidth, strlen (topics[i].command));
| ^~~
gio/gapplication-tool.c: In function ‘app_help’:
gio/gapplication-tool.c:90:21: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
90 | for (i = 0; i < G_N_ELEMENTS (topics); i++)
| ^
gio/gapplication-tool.c:117:25: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
117 | for (i = 0; i < G_N_ELEMENTS (substvars); i++)
| ^
gio/gapplication-tool.c:121:25: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
121 | for (i = 0; i < G_N_ELEMENTS (substvars); i++)
| ^
gio/gapplication-tool.c:137:21: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
137 | for (i = 0; i < G_N_ELEMENTS (topics); i++)
| ^
gio/gapplication-tool.c:140:21: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
140 | for (i = 0; i < G_N_ELEMENTS (topics); i++)
| ^
Since the previous commit, the generic `GInputStream` implementation of
`skip()` is now equivalent, and results in the same calls to `lseek()`.
Heavily based on an approach by Dan Winship in
https://bugzilla.gnome.org/show_bug.cgi?id=681374.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #587
The default implementation of `g_input_stream_skip()` can skip off the
end of resizable streams, as that’s the behaviour of `g_seekable_seek()`
for that type of stream.
This has previously been fixed for local file input streams (commit
89f9615835), and a unit test added there.
However, the fix should be more generally made in `GInputStream`.
This commit reworks an old patch by Dan Winship on
https://bugzilla.gnome.org/show_bug.cgi?id=681374, which took that
approach.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #587
This is a workaround for the fact that forking without execing is not
easy to do correctly, and `GTestDBus` doesn’t do it correctly. However,
`GTestDBus` is de-facto deprecated and so putting any more effort in is
a waste.
This fixes an issue where a test would print duplicate output when
outputting to a fully-buffered FD, such as a pipe. This is because the
buffer is non-empty before the `fork()`, and ends up duplicated in the
parent and child processes, both of which later flush the duplicated
buffer contents.
Diagnosed and fix suggested by Simon McVittie.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2322
Swedish as spoken in El Salvador is not listed in
/usr/share/i18n/SUPPORTED, and in any case is probably not what we meant.
A more plausible language code would be Swedish as spoken in Sweden.
Prompted by improving the Debian packaging of GLib to generate most of
the language codes mentioned in the tests, so that we can have better
test coverage.
Signed-off-by: Simon McVittie <smcv@collabora.com>
It’s not feasible to test that the require-same-user flag can cause
authentication to fail, as that would require the build environment to
have two users available. We can, however, test that it passes when
authenticating a client and server running under the same user account.
I have manually tested that the new flag works, by running the following
as user A:
```
`$prefix/gdbus-daemon --print-env &`
gdbus call --session --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.ListNames
```
And then running the `gdbus call` command again as user B (with the same
value for `DBUS_SESSION_BUS_ADDRESS` in the environment), which
produces:
```
Error connecting: Unexpected lack of content trying to read a line
```
(an authentication rejection)
Commenting out the use of
`G_DBUS_SERVER_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER` from
`gdbusdaemon.c`, the `gdbus call` command succeeds for both users.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
This doesn’t change the `GDBusDaemon` behaviour, but does simplify the
code a little.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #1804
This eliminates a common use case for the
`GDBusAuthObserver::authorize-authenticated-peer` signal, which is often
implemented incorrectly by people.
Suggested by Simon McVittie.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #1804
These should never have been allowed; they will result in precondition
failures from the `GKeyFile` later on in the code.
A test will be added for this shortly.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fix an effective regression in commit
7781a9cbd2, which happens when
`convert_path()` is called with a `key` which contains no slashes. In
that case, the `key` is entirely the `basename`.
Prior to commit 7781a9cb, the code worked through a fluke of `i == -1`
cancelling out with the various additions in the `g_memdup()` call, and
effectively resulting in `g_strdup (key)`.
Spotted by Guido Berhoerster.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
gio/glib-compile-resources.c: In function ‘parse_resource_file’:
gio/glib-compile-resources.c:553:3: error: missing initializer for field ‘passthrough’ of ‘GMarkupParser’ {aka ‘struct _GMarkupParser’}
553 | GMarkupParser parser = { start_element, end_element, text };
| ^~~~~~~~~~~~~
gio/gio-tool-tree.c: In function ‘do_tree’:
gio/gio-tool-tree.c:124:22: error: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’
124 | for (n = 0; n < level; n++)
| ^
gio/gio-tool-tree.c:197:21: error: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’
197 | for (n = 0; n < level; n++)
| ^
gio/gio-tool.c: In function ‘attribute_flags_to_string’:
gio/gio-tool.c:171:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’
171 | for (i = 0; i < G_N_ELEMENTS (flag_descr); i++)
| ^
gio/glib-compile-schemas.c: In function ‘parse_gschema_files’:
gio/glib-compile-schemas.c:1773:3: error: missing initializer for field ‘passthrough’ of ‘GMarkupParser’ {aka ‘struct _GMarkupParser’}
1773 | GMarkupParser parser = { start_element, end_element, text };
| ^~~~~~~~~~~~~
gio/glib-compile-schemas.c: In function ‘main’:
gio/glib-compile-schemas.c:2176:5: error: missing initializer for field ‘arg_description’ of ‘GOptionEntry’ {aka ‘struct _GOptionEntry’}
2176 | { "allow-any-name", 0, 0, G_OPTION_ARG_NONE, &allow_any_name, N_("Do not enforce key name restrictions") },
| ^
gio/glib-compile-schemas.c: In function ‘key_state_set_range’:
gio/glib-compile-schemas.c:376:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
376 | for (i = 0; i < G_N_ELEMENTS (table); i++)
| ^
gio/glib-compile-schemas.c: In function ‘key_state_serialise’:
gio/glib-compile-schemas.c:714:29: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
714 | for (i = 0; i < size / sizeof (guint32); i++)
| ^
gio/gsettings-mapping.c: In function ‘g_settings_set_mapping_int’:
gio/gsettings-mapping.c:65:23: error: comparison of integer expressions of different signedness: ‘gint64’ {aka ‘long int’} and ‘long unsigned int’
65 | if (0 <= l && l <= G_MAXUINT64)
| ^~
gio/gsettings-mapping.c: In function ‘g_settings_set_mapping_float’:
gio/gsettings-mapping.c:120:23: error: comparison of integer expressions of different signedness: ‘gint64’ {aka ‘long int’} and ‘long unsigned int’
120 | if (0 <= l && l <= G_MAXUINT64)
| ^~
gio/gsettings-mapping.c: In function ‘g_settings_get_mapping_int’:
gio/gsettings-mapping.c:224:27: error: comparison of integer expressions of different signedness: ‘gint64’ {aka ‘long int’} and ‘long unsigned int’
224 | return (0 <= l && l <= G_MAXUINT64);
| ^~
gio/gsettings-mapping.c: In function ‘g_settings_get_mapping_float’:
gio/gsettings-mapping.c:269:27: error: comparison of integer expressions of different signedness: ‘gint64’ {aka ‘long int’} and ‘long unsigned int’
269 | return (0 <= l && l <= G_MAXUINT64);
| ^~
The GDBusConnectionFlags and GDBusServerFlags can affect how we carry
out authentication and authorization, either making it more or less
restrictive, so it's desirable to "fail closed" if a program is compiled
against a new version of GLib but run against an old version.
Signed-off-by: Simon McVittie <smcv@collabora.com>
The intention here was to assert that the length of the password fits
in a gssize. Passwords more than half the size of virtual memory are
probably excessive.
Fixes: a8b204ff "gtlspassword: Forbid very long TLS passwords"
Signed-off-by: Simon McVittie <smcv@collabora.com>
gio/gsettingsschema.c: In function ‘parse_into_text_tables’:
gio/gsettingsschema.c:682:3: error: missing initializer for field ‘passthrough’ of ‘GMarkupParser’ {aka ‘struct _GMarkupParser’}
682 | GMarkupParser parser = { start_element, end_element, text };
| ^~~~~~~~~~~~~
gio/gsettingsschema.c:683:3: error: missing initializer for field ‘gettext_domain’ of ‘TextTableParseInfo’ [-Werror=missing-field-initializers]
683 | TextTableParseInfo info = { summaries, descriptions };
| ^~~~~~~~~~~~~~~~~~
gio/gmenu.c: In function ‘g_menu_remove’:
gio/gmenu.c:483:47: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
483 | g_return_if_fail (0 <= position && position < menu->items->len);
| ^
gio/gmenu.c: In function ‘g_menu_insert_item’:
gio/gmenu.c:165:32: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
165 | if (position < 0 || position > menu->items->len)
| ^
gio/glocalfileinfo.c: In function ‘get_access_rights’:
gio/glocalfileinfo.c:932:9: error: comparison of integer expressions of different signedness: ‘uid_t’ {aka ‘unsigned int’} and ‘int’
932 | uid == parent_info->owner ||
| ^~
gio/glocalfileinfo.c: In function ‘read_link’:
gio/glocalfileinfo.c:188:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
188 | if (read_size < size)
| ^
The public API `g_tls_password_set_value_full()` (and the vfunc it
invokes) can only accept a `gssize` length. Ensure that nul-terminated
strings passed to `g_tls_password_set_value()` can’t exceed that length.
Use `g_memdup2()` to avoid an overflow if they’re longer than
`G_MAXUINT` similarly.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2319
Don’t use an `int`, that’s potentially too small. In practical terms,
this is not a problem, since no socket address is going to be that big.
By making these changes we can use `g_memdup2()` without warnings,
though. Fewer warnings is good.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2319
Previously, the code in `convert_path()` could not handle keys longer
than `G_MAXINT`, and would overflow if that was exceeded.
Convert the code to use `gsize` and `g_memdup2()` throughout, and
change from identifying the position of the final slash in the string
using a signed offset `i`, to using a pointer to the character (and
`strrchr()`). This allows the slash to be at any position in a
`G_MAXSIZE`-long string, without sacrificing a bit of the offset for
indicating whether a slash was found.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2319
This allows it to handle strings up to length `G_MAXSIZE` — previously
it would overflow with such strings.
Update the several copies of it identically.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2319
Previously it was handled as a `gssize`, which meant that if the
`stop_chars` string was longer than `G_MAXSSIZE` there would be an
overflow.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2319
The members of `URL_COMPONENTS` (`winhttp_file->url`) are `DWORD`s, i.e.
32-bit unsigned integers. Adding to and multiplying them may cause them
to overflow the unsigned integer bounds, even if the result is passed to
`g_memdup2()` which accepts a `gsize`.
Cast the `URL_COMPONENTS` members to `gsize` first to ensure that the
arithmetic is done in terms of `gsize`s rather than unsigned integers.
Spotted by Sebastian Dröge.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2319
Convert all the call sites which use `g_memdup()`’s length argument
trivially (for example, by passing a `sizeof()`), so that they use
`g_memdup2()` instead.
In almost all of these cases the use of `g_memdup()` would not have
caused problems, but it will soon be deprecated, so best port away from
it.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2319
We're using "setuid" here as shorthand for any elevated privileges
that should make us distrust the caller: setuid, setgid, filesystem
capabilities, more obscure Linux things that set the AT_SECURE flag
(such as certain AppArmor transitions), and their equivalents on
other operating systems. This is fine if we do it consistently, but
I'm about to add a check for whether we are *literally* setuid,
which would be particularly confusing without a rename.
Signed-off-by: Simon McVittie <smcv@collabora.com>
gio/ghttpproxy.c: In function ‘g_http_proxy_connect’:
gio/ghttpproxy.c:245:17: error: comparison of integer expressions of different signedness: ‘gsize’ {aka ‘long unsigned int’} and ‘int’
245 | if (nread == -1)
| ^~
gio/ghttpproxy.c:253:22: error: comparison of integer expressions of different signedness: ‘gssize’ {aka ‘long int’} and ‘gsize’ {aka ‘long unsigned int’}
253 | if (bytes_read == buffer_length)
| ^~
Various tests have leaks where it isn't clear whether the data is
intentionally not freed, or leaked due to a bug. If we mark these
tests as TODO, we can skip them under AddressSanitizer and get the
rest to pass, giving us a baseline from which to avoid regressions.
Signed-off-by: Simon McVittie <smcv@collabora.com>
AddressSanitizer, UndefinedBehaviourSanitizer and probably others
involve adding instrumentation into the code under test, which doesn't
go well with LD_PRELOAD modules that absolutely need to be
self-contained.
Signed-off-by: Simon McVittie <smcv@collabora.com>
gio/gapplication.c: In function ‘g_application_parse_command_line’:
gio/gapplication.c:545:11: error: missing initializer for field ‘arg_description’ of ‘GOptionEntry’ {aka ‘struct _GOptionEntry’}
545 | N_("Enter GApplication service mode (use from D-Bus service files)") },
| ^~
gio/gapplication.c:557:11: error: missing initializer for field ‘arg_description’ of ‘GOptionEntry’ {aka ‘struct _GOptionEntry’}
557 | N_("Override the application’s ID") },
| ^~
gio/gapplication.c:569:11: error: missing initializer for field ‘arg_description’ of ‘GOptionEntry’ {aka ‘struct _GOptionEntry’}
569 | N_("Replace the running instance") },
| ^~
gio/gdbusconnection.c: In function ‘g_dbus_connection_register_object_with_closures’:
gio/gdbusconnection.c:5527:5: error: missing initializer for field ‘padding’ of ‘GDBusInterfaceVTable’ {aka ‘struct _GDBusInterfaceVTable’}
5527 | };
| ^
gio/gdelayedsettingsbackend.c: In function ‘delayed_backend_path_writable_changed’:
gio/gdelayedsettingsbackend.c:406:7: error: missing initializer for field ‘index’ of ‘CheckPrefixState’
406 | CheckPrefixState state = { path, g_new (const gchar *, n_keys) };
| ^~~~~~~~~~~~~~~~
With bash completion version lesser than 2.10, only prefix is defined
while for greater version it is datadir.
Closes#1054
Signed-off-by: Frederic Martinsons <frederic.martinsons@sigfox.com>
We format the message into a string twice, once for each byte-order,
but only return the one corresponding to the last byte-order to the
caller. This means we need to free the first one.
Signed-off-by: Simon McVittie <smcv@collabora.com>
- use watcher auto start flag.
- use watch_name_on_connection_with_closures.
- use an existing service name for auto start.
Closes#2011
Signed-off-by: Frederic Martinsons <frederic.martinsons@sigfox.com>
Where the early call to g_socket_set_option() fails because of
check_socket() failing due to `inited` still being FALSE.
This brings 634b692 back into working order, by fixing the regression
introduced in 39f047e.
Co-authored-by: Ole André Vadla Ravnås <oleavr@gmail.com>
gio/gapplicationimpl-dbus.c: In function ‘g_application_impl_command_line’:
gio/gapplicationimpl-dbus.c:772:3: error: ‘static’ is not at beginning of declaration
772 | const static GDBusInterfaceVTable vtable = {
| ^~~~~
gio/gapplicationimpl-dbus.c:774:3: error: missing initializer for field ‘get_property’ of ‘GDBusInterfaceVTable’ {aka ‘const struct _GDBusInterfaceVTable’}
774 | };
| ^
gio/gapplicationimpl-dbus.c: In function ‘g_application_impl_attempt_primary’:
gio/gapplicationimpl-dbus.c:364:3: error: ‘static’ is not at beginning of declaration
364 | const static GDBusInterfaceVTable vtable = {
| ^~~~~
gio/gapplicationimpl-dbus.c:368:3: error: missing initializer for field ‘padding’ of ‘GDBusInterfaceVTable’ {aka ‘const struct _GDBusInterfaceVTable’}
368 | };
| ^
gio/gmenuexporter.c: In function ‘g_dbus_connection_export_menu_model’:
gio/gmenuexporter.c:787:3: error: missing initializer for field ‘get_property’ of ‘GDBusInterfaceVTable’ {aka ‘const struct _GDBusInterfaceVTable’}
787 | };
| ^
gio/gsocketlistener.c: In function ‘g_socket_listener_close’:
gio/gsocketlistener.c:1019:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
1019 | for (i = 0; i < listener->priv->sockets->len; i++)
| ^
gio/gsocketlistener.c: In function ‘g_socket_listener_set_backlog’:
gio/gsocketlistener.c:993:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
993 | for (i = 0; i < listener->priv->sockets->len; i++)
| ^
gio/gsocketlistener.c: In function ‘add_sources’:
gio/gsocketlistener.c:612:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
612 | for (i = 0; i < listener->priv->sockets->len; i++)
| ^
gio/gactiongroupexporter.c: In function ‘g_dbus_connection_export_action_group’:
gio/gactiongroupexporter.c:542:3: error: missing initializer for field ‘get_property’ of ‘GDBusInterfaceVTable’ {aka ‘const struct _GDBusInterfaceVTable’}
542 | };
| ^
gio/gnetworkmonitornetlink.c: In function ‘remove_network’:
gio/gnetworkmonitornetlink.c:272:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
272 | for (i = 0; i < nl->priv->dump_networks->len; i++)
| ^
These two APIs are useful to publish an object which path content is not
controlled (e.g. dynamically built or coming from external source).
Closes#968
(Rebased and tweaked by Frederic Martinsons)
Signed-off-by: Frederic Martinsons <frederic.martinsons@sigfox.com>
This makes the tests a whole lot closer to being valgrind-clean, and
revealed a few legitimate memory leaks in amongst the noise caused by
keeping the singleton GSettingsBackend around for the lifetime of the
process.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
While all of the current callers of _g_io_module_get_default() want to
cache the returned GObject for the lifetime of the process, that doesn’t
necessarily have to be the case, so let callers make that decision on a
case-by-case basis.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
So we can still run at full speed on modern kernels in cases where an
old toolchain was used to build GLib. This is often done deliberately
to allow shipping binaries that need to run on a wide range of systems.
gio/gdbusdaemon.c: In function ‘match_new’:
gio/gdbusdaemon.c:449:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
449 | for (i = 0; i < elements->len; i++)
| ^
gio/gdbusdaemon.c: In function ‘is_key’:
gio/gdbusdaemon.c:213:11: error: comparison of integer expressions of different signedness: ‘gsize’ {aka ‘long unsigned int’} and ‘long int’
213 | if (len != key_end - key_start)
| ^~
gio/gcontenttype.c: In function ‘load_comment_for_mime_helper’:
gio/gcontenttype.c:409:3: error: missing initializer for field ‘passthrough’ of ‘GMarkupParser’ {aka ‘struct _GMarkupParser’}
409 | };
| ^
gio/gdesktopappinfo.c: In function ‘g_app_info_get_all’:
gio/gdesktopappinfo.c:4597:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
4597 | for (i = 0; i < desktop_file_dirs->len; i++)
| ^
gio/gdesktopappinfo.c: In function ‘g_desktop_app_info_search’:
gio/gdesktopappinfo.c:4517:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
4517 | for (i = 0; i < desktop_file_dirs->len; i++)
| ^
gio/gdesktopappinfo.c: In function ‘g_desktop_app_info_get_implementations’:
gio/gdesktopappinfo.c:4451:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
4451 | for (i = 0; i < desktop_file_dirs->len; i++)
| ^
gio/gdesktopappinfo.c: In function ‘g_desktop_app_info_get_desktop_ids_for_content_type’:
gio/gdesktopappinfo.c:4154:19: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
4154 | for (j = 0; j < desktop_file_dirs->len; j++)
| ^
gio/gdesktopappinfo.c:4158:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’} [-Werror=sign-compare]
4158 | for (i = 0; i < hits->len; i++)
| ^
gio/gdesktopappinfo.c: In function ‘get_list_of_mimetypes’:
gio/gdesktopappinfo.c:4116:21: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
4116 | for (i = 0; i < array->len; i++)
| ^
gio/gdesktopappinfo.c: In function ‘g_desktop_app_info_launch_uris_with_spawn’:
gio/gdesktopappinfo.c:2804:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’
2804 | for (i = 0; i < G_N_ELEMENTS (wrapper_argv); i++)
| ^
gio/gdesktopappinfo.c: In function ‘desktop_file_dirs_lock’:
gio/gdesktopappinfo.c:1564:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
1564 | for (i = 0; i < desktop_file_dirs->len; i++)
| ^
gio/gdesktopappinfo.c: In function ‘array_contains’:
gio/gdesktopappinfo.c:1193:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
1193 | for (i = 0; i < array->len; i++)
| ^
gio/gdesktopappinfo.c: In function ‘desktop_file_dir_unindexed_setup_search’:
gio/gdesktopappinfo.c:1114:25: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1114 | for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
| ^
gio/gmemoryinputstream.c: In function ‘g_memory_input_stream_seek’:
gio/gmemoryinputstream.c:479:32: error: comparison of integer expressions of different signedness: ‘goffset’ {aka ‘long int’} and ‘gsize’ {aka ‘long unsigned int’}
479 | if (absolute < 0 || absolute > priv->len)
| ^
gio/glocalfilemonitor.c: In function ‘g_file_monitor_source_new’:
gio/glocalfilemonitor.c:653:3: error: missing initializer for field ‘closure_callback’ of ‘GSourceFuncs’ {aka ‘struct _GSourceFuncs’}
653 | };
| ^
gio/gsubprocess.c: In function ‘initable_init’:
gio/gsubprocess.c:587:26: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
587 | g_assert (0 < s && s < sizeof self->identifier);
| ^
gio/gsocketcontrolmessage.c: In function ‘g_socket_control_message_deserialize’:
gio/gsocketcontrolmessage.c:189:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
189 | for (i = 0; i < n_message_types; i++)
| ^
gio/gsubprocess.c: In function ‘child_setup’:
gio/gsubprocess.c:271:56: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
271 | if (child_data->fds[i] != -1 && child_data->fds[i] != i)
| ^~
gio/gsocket.c: In function ‘g_socket_send_message_with_timeout’:
gio/gsocket.c:4528:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘const unsigned int’}
4528 | for (i = 0; i < _message->num_vectors; i++) \
| ^
gio/gsocket.c: In function ‘g_socket_send_message_with_timeout’:
gio/gsocket.c:4543:19: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘const unsigned int’}
4543 | for (i = 0; i < _message->num_control_messages; i++) \
| ^
gio/gsocket.c: In function ‘g_socket_send_messages_with_timeout’:
gio/gsocket.c:5133:19: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
5133 | for (i = 0; i < num_messages; ++i)
| ^
gio/gsocket.c:5152:33: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
5152 | for (num_sent = 0; num_sent < num_messages;)
| ^
gio/gsimpleproxyresolver.c: In function ‘ignore_host’:
gio/gsimpleproxyresolver.c:271:18: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
271 | for (i = 0; i < priv->ignore_ips->len; i++)
| ^
The explanation of this bug has been mentioned in !1823, basically
it fixes some possible integer overflow when message buffer size
is more than G_MAXSSIZE.
gio/gpollableoutputstream.c: In function ‘g_pollable_output_stream_default_writev_nonblocking’:
gio/gpollableoutputstream.c:217:15: error: comparison of integer expressions of different signedness: ‘gssize’ {aka ‘long int’} and ‘gsize’ {aka ‘const long unsigned int’}
217 | if (res < vectors[i].size)
| ^
gio/goutputstream.c: In function ‘g_output_stream_real_writev’:
gio/goutputstream.c:2347:15: error: comparison of integer expressions of different signedness: ‘gssize’ {aka ‘long int’} and ‘gsize’ {aka ‘const long unsigned int’}
2347 | if (res < vectors[i].size)
| ^
gio/gcredentials.c: In function ‘linux_ucred_check_valid’:
gio/gcredentials.c:317:22: error: comparison of integer expressions of different signedness: ‘uid_t’ {aka ‘unsigned int’} and ‘int’
317 | || native->uid == -1
| ^~
gio/gcredentials.c:318:22: error: comparison of integer expressions of different signedness: ‘gid_t’ {aka ‘unsigned int’} and ‘int’
318 | || native->gid == -1)
| ^~
gio/gcredentials.c: In function ‘g_credentials_set_unix_user’:
gio/gcredentials.c:639:29: error: comparison of integer expressions of different signedness: ‘uid_t’ {aka ‘unsigned int’} and ‘int’
639 | g_return_val_if_fail (uid != -1, FALSE);
| ^~
Split out XDG_CURRENT_DESKTOP handling to a separate function and make
sure that it drops all the invalid entries properly. Earlier a bad
entry could slip through the checks by sitting just after another bad
entry, like in env being set to `invalid1!:invalid2!`, where
`invalid2!` could slip the checks.
It occasionally fails in CI with output like:
```
196/274 glib:gio / gdbus-connection-slow FAIL 0.54 s (killed by signal 6 SIGABRT)
--- command ---
G_TEST_BUILDDIR='/builds/pwithnall/glib/_build/gio/tests' G_TEST_SRCDIR='/builds/pwithnall/glib/gio/tests' GIO_MODULE_DIR='' /builds/pwithnall/glib/_build/gio/tests/gdbus-connection-slow
--- stdout ---
\# random seed: R02S4eb186e89e2472eedd11538b37192543
1..2
\# Start of gdbus tests
\# Start of connection tests
Bail out! GLib-GIO:ERROR:../gio/tests/gdbus-connection-slow.c:98:test_connection_flush: assertion failed (error == NULL): Child process killed by signal 11 (g-exec-error-quark, 19)
--- stderr ---
**
GLib-GIO:ERROR:../gio/tests/gdbus-connection-slow.c:98:test_connection_flush: assertion failed (error == NULL): Child process killed by signal 11 (g-exec-error-quark, 19)
cleaning up pid 12991
```
which is not very helpful. Add some more debug output to print the
stdout and stderr of the child process, to hopefully give an insight
into why it’s dying with signal 11 (sigsegv).
I can’t reproduce the sigsegv locally.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
As with previous commits, this could have been used to load private data
for an unprivileged caller.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2168
It could have been used to load private data which would not normally be
accessible to an unprivileged caller.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2168
Its components are used to build filenames, so if the value of
`XDG_CURRENT_DESKTOP` comes from an untrusted caller (as can happen in
setuid programs), using it unvalidated may be unsafe.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2168
As with the previous commit, it’s unsafe to trust the environment when
running as setuid, as it comes from an untrusted caller. In particular,
with D-Bus, the caller could set up a fake ‘system’ bus which fed
incorrect data to this process.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2168
Even if the modules in the given directory never get chosen to be used,
loading arbitrary code from a user-provided directory is not safe when
running as setuid, as the process’ environment comes from an untrusted
source.
Also ignore `GIO_EXTRA_MODULES`.
Spotted by Simon McVittie.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2168
Clang says:
../gio/glocalfile.c:2090:11: warning: variable 'success' is used uninitialized whenever 'if' condition is false [-Wsometimes-uninitialized]
if (trashdir == NULL)
^~~~~~~~~~~~~~~~
../gio/glocalfile.c:2133:12: note: uninitialized use occurs here
if (!success)
^~~~~~~
../gio/glocalfile.c:2090:7: note: remove the 'if' if its condition is always true
if (trashdir == NULL)
^~~~~~~~~~~~~~~~~~~~~
../gio/glocalfile.c:2041:23: note: initialize the variable 'success' to silence this warning
gboolean success;
^
= 0
So just do that.
Most variables were, but a few were not declared as local, and hence
leaked into the calling environment every time someone tab-completed the
`gio` command.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2275
- When querying a TCP socket, getsockopt() may succeed but the resulting
`optlen` will be zero. This means we'd previously be reading
uninitialized stack memory in such cases.
- After a file-descriptor has gone through FD-passing, getsockopt() may
fail with EINVAL. At least this is the case with TCP sockets.
- While at it also use SOL_LOCAL instead of hard-coding its value.
Contrary to what the WSARecvFrom seem to imply, a UDP socket is perfectly recoverable and usable after a WSAECONNRESET error (and, I assume, WSAENETRESET).
However GSocket condition has the FD_READ bit set after a UDP socket fails with WSAECONNRESET, even if no data is available on the socket anymore; this causes select calls to report the socket as readable when, in fact, it's not.
The change resets FD_READ flag on a socket upon the above error conditions; there's no 'if' to filter between datagram and stream sockets as the change should be harmless in the case of stream sockets which are, however, very unlikely to be usable after a WSAECONNRESET.
The list is sorted in ascending order, which means that to put
verbs alphabetically we need to sort ealier verbs with -1. Same for
the "open" verb and the preferred verb (if any).
* UWP apps that have low registry footprint might end up with chosen_handler == NULL.
Ensure that this doesn't happen.
* UWP apps don't need verbs for URIs, but we do need verbs to have a link to an app
(since handlers don't contain app fields). Work around this by adding an "open" verb
to each UWP URI handler.
* Duplicate the code that inserts extension handler verbs into the app to also insert
URI handler verbs. This allows URI-only apps to be used correctly later on (otherwise
GLib errors out, saying that the app has no verbs).
Use pretty name as the result of _name(), if available. This is
more in line with what .desktop files return. Canonical name
may be completely unintelligible.
MSDN doesn't say much on this subject, but i've seen apps in the wild
that have the "shell" subkey with verbs *either* in the root app key *or*
in the "Capabilities" subkey of the root key. Accommodate either case by trying both
(root key gets a priority, since this is how MS Address Book is registered -
assume that MS knows how to do this the right way).
This function enumerates all user-accessible UWP packages
and calls the user-provided callback for each package.
This can be used to make GLib aware of the UWP applications
installed in the system.
The function works by using IPackageManager/IPackage UWP interfaces
and XmlLite COM library to parse package manifests.
The function requires COM, and initializes it to a single-thread
appartment model. To ensure this doesn't break anything, either
only use it in a separate thread (COM is initialized on a per-thread
basis), or make sure that the main thread also uses the same COM
model (it's OK to initialize COM multiple times, as long as the same
model is used and as long as init/uninit calls are paired correctly).
MinGW-w64 lacks the appropriate headers, so we have to add them
here. Note that these only have the C versions (normally these
things come in both C and C++ flavours), since that's what we use.
Also note that some of the functions that we don't use (but must
describe to maintain binary compatibility) were altered to use
IUnknown (basically, an untyped pointer) instead of the appropriate
object types, as adding these types would require other types,
which would pull even more types, forcing us to drag half of the
UWP headers in here. By replacing unused types with IUnknown we
can trim a lot of branches from the dependency graph.
This is a COM object that implements IStream by using a HANDLE
and WinAPI file functions to access the file (only a file; pipes
are not supported). Only supports synchronous access (this is
a feature - the APIs that read from this stream internally will
never return the COM equivalent of EWOULDBLOCK, which greatly
simplifies their use).
Just embed a PNG instead. gdk-pixbuf deprecated its pixdata support in
version 2.32, in 2015.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #1281
gio/gcredentials.c: In function ‘g_credentials_to_string’:
gio/gcredentials.c:238:31: error: comparison of integer expressions of different signedness: ‘uid_t’ {aka ‘unsigned int’} and ‘int’
238 | if (credentials->native.uid != -1)
| ^~
gio/gcredentials.c:240:31: error: comparison of integer expressions of different signedness: ‘gid_t’ {aka ‘unsigned int’} and ‘int’
240 | if (credentials->native.gid != -1)
| ^~
gio/gfileattribute.c: In function ‘escape_byte_string’:
gio/gfileattribute.c:286:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’}
286 | for (i = 0; i < len; i++)
| ^
gio/gfileattribute.c:299:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’}
299 | for (i = 0; i < len; i++)
| ^
gio/gicon.c: In function ‘g_icon_to_string_tokenized’:
gio/gicon.c:165:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
165 | for (i = 0; i < tokens->len; i++)
| ^
gio/gfileinfo.c: In function ‘g_file_info_remove_attribute’:
gio/gfileinfo.c:706:9: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
706 | if (i < info->attributes->len &&
| ^
Fix signedness warning in gio/gfileinfo.c:g_file_info_create_value()
gio/gfileinfo.c: In function ‘g_file_info_create_value’:
gio/gfileinfo.c:1084:9: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
1084 | if (i < info->attributes->len &&
| ^
Fix signedness warning in gio/gfileinfo.c:matcher_matches_id()
gio/gfileinfo.c: In function ‘matcher_matches_id’:
gio/gfileinfo.c:2624:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
2624 | for (i = 0; i < matcher->sub_matchers->len; i++)
| ^
Fix signedness warnings in gio/gfileinfo.c:g_file_attribute_matcher_enumerate_namespace()
gio/gfileinfo.c: In function ‘g_file_attribute_matcher_enumerate_namespace’:
gio/gfileinfo.c:2713:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
2713 | for (i = 0; i < matcher->sub_matchers->len; i++)
| ^
gio/gfileinfo.c:2715:27: error: comparison of integer expressions of different signedness: ‘guint32’ {aka ‘unsigned int’} and ‘int’
2715 | if (sub_matchers[i].id == ns_id)
| ^~
Fix signedness warning in gio/gfileinfo.c:g_file_attribute_matcher_enumerate_next()
gio/gfileinfo.c: In function ‘g_file_attribute_matcher_enumerate_next’:
../glib.git/gio/gfileinfo.c:2752:13: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’} [-Werror=sign-compare]
2752 | if (i < matcher->sub_matchers->len)
| ^
gio/gfileinfo.c: In function ‘g_file_info_list_attributes’:
gio/gfileinfo.c:645:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
645 | for (i = 0; i < info->attributes->len; i++)
| ^
gio/gfileinfo.c: In function ‘g_file_info_has_namespace’:
gio/gfileinfo.c:610:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
610 | for (i = 0; i < info->attributes->len; i++)
| ^
gio/gfileinfo.c: In function ‘g_file_info_find_value’:
gio/gfileinfo.c:543:9: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
543 | if (i < info->attributes->len &&
| ^
gio/gfileinfo.c: In function ‘g_file_info_clear_status’:
gio/gfileinfo.c:499:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
499 | for (i = 0; i < info->attributes->len; i++)
| ^
gio/gfileinfo.c: In function ‘g_file_info_set_attribute_mask’:
gio/gfileinfo.c:453:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
453 | for (i = 0; i < info->attributes->len; i++)
| ^
gio/gfileinfo.c: In function ‘g_file_info_copy_into’:
gio/gfileinfo.c:385:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
385 | for (i = 0; i < dest_info->attributes->len; i++)
| ^
gio/gfileinfo.c: In function ‘g_file_info_finalize’:
gio/gfileinfo.c:327:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
327 | for (i = 0; i < info->attributes->len; i++)
| ^
gio/gdatainputstream.c: In function ‘scan_for_chars’:
gio/gdatainputstream.c:879:40: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
879 | for (i = 0; checked < available && i < peeked; i++)
| ^
gio/gdatainputstream.c: In function ‘scan_for_newline’:
gio/gdatainputstream.c:654:40: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
654 | for (i = 0; checked < available && i < peeked; i++)
| ^
gio/gliststore.c: In function ‘g_list_store_insert’:
gio/gliststore.c:272:30: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint’ {aka ‘int’}
272 | g_return_if_fail (position <= g_sequence_get_length (store->items));
| ^~
gio/gliststore.c: In function ‘g_list_store_splice’:
gio/gliststore.c:482:21: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘guint’ {aka ‘unsigned int’}
482 | for (i = 0; i < n_additions; i++)
| ^
gio/gcancellable.c:773:1: error: missing initializer for field ‘closure_marshal’ of ‘GSourceFuncs’ {aka ‘struct _GSourceFuncs’}
773 | };
| ^
In file included from glib/giochannel.h:33,
from glib/glib.h:54,
from gio/gcancellable.c:22:
glib/gmain.h:277:23: note: ‘closure_marshal’ declared here
277 | GSourceDummyMarshal closure_marshal; /* Really is of type GClosureMarshal */
| ^~~~~~~~~~~~~~~
gio/gcontextspecificgroup.c: In function ‘g_context_specific_source_new’:
gio/gcontextspecificgroup.c:77:3: error: missing initializer for field ‘closure_callback’ of ‘GSourceFuncs’ {aka ‘struct _GSourceFuncs’}
77 | };
| ^
In file included from glib/giochannel.h:33,
from glib/glib.h:54,
from gobject/gbinding.h:28,
from glib/glib-object.h:22,
from gio/gcontextspecificgroup.h:23,
from gio/gcontextspecificgroup.c:22:
glib/gmain.h:276:19: note: ‘closure_callback’ declared here
276 | GSourceFunc closure_callback;
| ^~~~~~~~~~~~~~~~
gio/inotify/inotify-kernel.c: In function ‘ik_source_new’:
gio/inotify/inotify-kernel.c:377:3: error: missing initializer for field ‘finalize’ of ‘GSourceFuncs’ {aka ‘struct _GSourceFuncs’}
377 | };
| ^
In file included from glib/giochannel.h:33,
from glib/glib.h:54,
from gio/inotify/inotify-kernel.c:30:
glib/gmain.h:272:14: note: ‘finalize’ declared here
272 | void (*finalize) (GSource *source); /* Can be NULL */
| ^~~~~~~~
This commit only looks at the `Returns:` lines in the documentation, and
has examined all of them in the file. Function arguments have not been
checked.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2227
This commit only looks at the `Returns:` lines in the documentation, and
has examined all of them in the file. Function arguments have not been
checked.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2227
This commit only looks at the `Returns:` lines in the documentation, and
has examined all of them in the file. Function arguments have not been
checked.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2227
This commit only looks at the `Returns:` lines in the documentation, and
has examined all of them in the file. Function arguments have not been
checked.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2227
The version of `black` on the CI server wanted these changes. Make them
to keep the `style-check-diff` CI job from constantly failing.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Try and catch programmer errors in third-party implementations of
`dbus_register()`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1188
NULL is valid return value for the g_unix_mount_get_options function
because mount options are currently provided only by libmount implementation.
However, the gio tool passes the returned value to the g_strescape function
without checking, which produces the following critical warning:
GLib-CRITICAL **: 13:47:15.294: g_strescape: assertion 'source != NULL' failed
Let's add the missing check to prevent the critical warnings.
These might help catch the problem in #2119 earlier on, and provide more
information about its root cause.
They should not affect behaviour in normal application usage.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2119
This is technically an API break, as the following assignment may now
raise warnings in user code:
```
gchar *filename = g_osx_app_info_get_filename (app_info);
```
However, from code search it seems like the number of users of that
function is zero.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
This command will try to execute a desktop file, before that
it will load the input as a keyfile for checking its existence
and its validity (as a keyfile).
File arguments are allowed after the desktop file.
Closes#54
Signed-off-by: Frederic Martinsons <frederic.martinsons@sigfox.com>
Static analysis of the call to `g_dir_new_from_dirp()` is tricky,
because the call is across library boundaries and indirected through a
vfunc map because it’s private to libglib.
Help the static analyser by adding an assertion about the input and
output values for `g_dir_new_from_dirp()`.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
It search for attribute trash::orig-path and move the input file to it.
Possibly recreating the directory of orignal path and/or overwritting
the destination.
Closes#2098
Signed-off-by: Frederic Martinsons <frederic.martinsons@sigfox.com>
There were a couple of places where the return value wasn’t checked, and
hence failure could not be noticed.
Coverity CIDs: #1159435, #1159426
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
From:
9eb9c93275
"we found that the const security_context_t declarations in libselinux
are incorrect; const char * was intended, but const security_context_t
translates to char * const and triggers warnings on passing const char *
from the caller. Easiest fix is to replace them all with const char *."
And later marked deprecated in commit:
7a124ca275
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
These variables were already (correctly) accessed atomically. The
`volatile` qualifier doesn’t help with that.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #600
This should introduce no API changes. The
`g_dbus_error_register_error_domain()` function still (incorrectly) has
a `volatile` argument, but dropping that qualifier would be an API
break.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #600
This should introduce no API changes; there are public functions
exported by `GDBusConnection` which still have some (incorrectly)
`volatile` arguments, but dropping those qualifiers would be an API
break.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #600
These variables were already (correctly) accessed atomically. The
`volatile` qualifier doesn’t help with that.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #600
And drop the `volatile` qualifier from the variables, as that doesn’t
help with thread safety.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #600
http://isvolatileusefulwiththreads.in/c/
It’s possible that the variables here are only marked as volatile
because they’re arguments to `g_once_*()`. Those arguments will be
modified in a subsequent commit.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #600
These tests were originally written using the output directly from a
fuzzer which had triggered the bugs we’re testing for. However, that
means they’re liable to no longer test what they’re intended to test if
the `GDBusMessage` parsing code is changed to (for example) check for
certain errors earlier in future.
It’s better to only have one invalidity in each binary blob, so change
the test messages to all be valid apart from the specific thing they’re
testing for.
The changes were based on reading the D-Bus specification directly:
https://dbus.freedesktop.org/doc/dbus-specification.html
During these changes I found one problem in
`test_message_parse_deep_header_nesting()` where it wasn’t actually
nesting variants in the header deeply enough to trigger the bug it was
supposed to be testing for. Fixed that.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #1963
This commit is the unmodified results of running
```
black $(git ls-files '*.py')
```
with black version 19.10b0. See #2046.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Set counters for the number of running tasks and
for the max. threadpool size. These are meant to
get a sense for whether G_TASK_POOL_SIZE and related
constants are still suitable for current gio and
GTask usage patterns.
Previously it was considered a programming error to call these on
subprocesses created without the correct flags, but for bindings this
distinction is difficult to handle automatically.
Returning NULL instead does not cause any inconsistent behaviour and
simplifies the API.
As hidden file caches currently work, every look up on a directory caches
its .hidden file contents, and sets a 5s timeout to prune the directory
from the cache.
This creates a problem for usecases like Tracker Miners, which is in the
business of inspecting as many files as possible from as many directories
as possible in the shortest time possible. One timeout is created for each
directory, which possibly means gobbling thousands of entries in the hidden
file cache. This adds as many GSources to the glib worker thread, with the
involved CPU overhead in iterating those in its main context.
To fix this, use a unique timeout that will keep running until the cache
is empty. This will keep the overhead constant with many files/folders
being queried.
Continue to allow overriding the keyring dir, but don’t automatically
create it when running as root.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Coverity CID: #1432485
This is a regression from !1686. The tmp_error is no longer valid after
it is "considered" and cannot be used at this point. We should print the
error earlier instead.
Fixes#2233
This incidentally also exercises the intended pattern for sending fds in
a D-Bus message: the fd list is meant to contain exactly those fds that
are referenced by a handle (type 'h') in the body of the message, with
numeric handle value n corresponding to g_unix_fd_list_peek_fds(...)[n].
Being able to send and receive file descriptors that are not referenced by
a handle (as in OpenFile here) is a quirk of the GDBus API, and while it's
entirely possible in the wire protocol, other D-Bus implementations like
libdbus and sd-bus typically don't provide APIs that make this possible.
Reproduces: https://gitlab.gnome.org/GNOME/glib/-/issues/2074
Signed-off-by: Simon McVittie <smcv@collabora.com>
In the D-Bus wire protocol, the handle type (G_VARIANT_TYPE_HANDLE, h)
is intended to be an index/pointer into the implementation's closest
equivalent of GUnixFDList: its numeric value has no semantic meaning
(in the same way that the numeric values of pointers have no semantic
meaning), but a handle with value n acts as a reference to the nth fd
in the fd list.
GDBus provides a fairly direct mapping from the wire protocol to the
C API, which makes it technically possible to attach and use fds
without ever referring to them in the message body, and some
GLib-centric D-Bus APIs rely on this.
However, the other major implementations of D-Bus (libdbus and sd-bus)
transparently replace file descriptors with handles when building
messages, and transparently replace handles with file descriptors when
parsing messages. This means they cannot implement D-Bus APIs that do
not follow the conventional meaning of handles as indexes/pointers into
an equivalent of GUnixFDList.
For interoperability, we should encourage D-Bus API designers to follow
the convention, even though code written against GDBus doesn't strictly
need to do so.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Suppose we are sending a 5K message with fds (so data->blob points
to 5K of data, data->blob_size is 5K, and fd_list is non-null), but
the kernel is only accepting up to 4K with each sendmsg().
The first time we get into write_message_continue_writing(),
data->total_written will be 0. We will try to write the entire message,
plus the attached file descriptors; or if the stream doesn't support
fd-passing (not a socket), we need to fail with
"Tried sending a file descriptor on unsupported stream".
Because the kernel didn't accept the entire message, we come back in.
This time, we won't enter the Unix-specific block that involves sending
fds, because now data->total_written is 4K, and it would be wrong to try
to attach the same fds again. However, we also need to avoid failing
with "Tried sending a file descriptor on unsupported stream" in this
case. We just want to write out the data of the rest of the message,
starting from (blob + total_written) (in this exaple, the last 1K).
Resolves: https://gitlab.gnome.org/GNOME/glib/-/issues/2074
Signed-off-by: Simon McVittie <smcv@collabora.com>
This test ensures that g_socket_client_connect_to_host_async() fails if
it is cancelled, but it's not cancelled until after 1 millisecond. Our
CI testers are hitting that race window, and Milan is able to reproduce
the crash locally as well. Switching it from 1ms to 0ms is enough for
Milan to avoid the crash, but not enough for our CI, so let's move the
cancellation to a GSocketClientEvent callback where the timing is
completely deterministic.
Hopefully fixes#2221
g_has_typeof macro is wrongly in the public g_ namespace, internaly
symbols are usually in the glib_ namespace. This will also allow to
define glib_typeof differently on non-GNUC compilers (e.g. c++11
decltype).
This introduces no functional changes, but makes the refcount handling a
little easier to follow by no longer splitting a ref/unref pair across
three callbacks. Now, the ref/unref pairs are all within function-local
scopes.
Coverity CID: #1430783
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
By default, when using g_subprocess_launcher_take_fd() to pass an
FD to a child, the GSubprocessLauncher object also takes ownership
of the FD in the parent, and closes it during finalize(). This is
a reasonable assumption in the majority of the cases, but sometimes
it isn't a good idea.
An example is when creating a GSubprocessLauncher in JavaScript:
here, the destruction process is managed by the Garbage Collector,
which means that those sockets will remain opened for some time
after all the references to the object has been droped. This means
that it could be not possible to detect when the child has closed
that same FD, because in order to make that work, both FDs
instances (the one in the parent and the one in the children) must
be closed. This can be a problem in, as an example, a process that
launches a child that communicates with Wayland using an specific
socket (like when using the new API MetaWaylandClient).
Of course, it isn't a valid solution to manually call close() in
the parent process just after the call to spawn(), because the FD
number could be reused in the time between it is manually closed,
and when the object is destroyed and closes again that FD. If that
happens, it will close an incorrect FD.
One solution could be to call run_dispose() from Javascript on the
GSubprocessLauncher object, to force freeing the resources.
Unfortunately, the current code frees them in the finalize()
method, not in dispose() (this is fixed in !1670 (merged) ) but it
isn't a very elegant solution.
This proposal adds a new method, g_subprocess_launcher_close(),
that allows to close the FDs passed to the child. To avoid problems,
after closing an FD with this method, no more spawns are allowed.
Fix: https://gitlab.gnome.org/GNOME/glib/-/merge_requests/1677
Originally, GSocketClient returned whatever error occured last. Turns
out this doesn't work well in practice. Consider the following case:
DNS returns an IPv4 and IPv6 address. First we'll connect() to the
IPv4 address, and say that succeeds, but TLS is enabled and the TLS
handshake fails. Then we try the IPv6 address and receive ENETUNREACH
because IPv6 isn't supported. We wind up returning NETWORK_UNREACHABLE
even though the address can be pinged and a TLS error would be more
appropriate. So instead, we now try to return the error corresponding
to the latest attempted GSocketClientEvent in the connection process.
TLS errors take precedence over proxy errors, which take precedence
over connect() errors, which take precedence over DNS errors.
In writing this commit, I made several mistakes that were caught by
proxy-test.c, which tests using GSocketClient to make a proxy
connection. So although adding a new test to ensure we get the
best-possible error would be awkward, at least we have some test
coverage for the code that helped avoid introducing bugs.
Fixes#2211
We should never return unknown errors to the application. This would be
a glib bug.
I don't think it's currently possible to hit these cases, so asserts
should be OK. For this to happen, either (a) a GSocketAddressEnumerator
would have to return NULL on its first enumeration, without returning an
error, or (b) there would have to be a bug in our GSocketClient logic.
Either way, if such a bug were to exist, it would be better to surface
it rather than hide it.
These changes are actually going to be effectively undone in a
subsequent commit, as I'm refactoring the error handling, but the commit
history is a bit nicer with two separate commits, so let's go with two.
GSocketAddressEnumerator encapsulates the details of how DNS happens, so
we don't have to think about it. But we may have taken encapsulation a
bit too far, here. Usually, we resolve a domain name to a list of IPv4
and IPv6 addresses. Then we go through each address in the list and try
to connect to it. Name resolution happens exactly once, at the start.
It doesn't happen each time we enumerate the enumerator. In theory, it
*could*, because we've designed these APIs to be agnostic of underlying
implementation details like DNS and network protocols. But in practice,
we know that's not really what's happening. It's weird to say that we
are RESOLVING what we know to be the same name multiple times. Behind
the scenes, we're not doing that.
This also fixes#1994, where enumeration can end with a RESOLVING event,
even though this is supposed to be the first event rather than the last.
I thought this would be hard to fix, even requiring new public API in
GSocketAddressEnumerator to peek ahead to see if the next enumeration is
going to return NULL. Then I decided we should just fake it: always emit
both RESOLVING and RESOLVED at the same time right after each
enumeration. Finally, I realized we can emit them at the correct time if
we simply assume resolving only happens the first time. This seems like
the most elegant of the possible solutions.
Now, this is a behavior change, and arguably an API break, but it should
align better with reasonable expectations of how GSocketClientEvent
ought to work. I don't expect it to break anything besides tests that
check which order GSocketClientEvent events are emitted in. (Currently,
libsoup has such tests, which will need to be updated.) Ideally we would
have GLib-level tests as well, but in a concession to pragmatism, it's a
lot easier to keep network tests in libsoup.
This isn't an API guarantee, but it's a potentially-surprising
behavior difference between the sync and async functions that is good
to know about, especially because our sync and async functions are
normally identical.
The linux kernel does not know that the socket will be used
for connect or listen and if you bind() to a local address it must
reserve a random port (if port == 0) at bind() time, making very easy
to exhaust the ~32k port range, setting IP_BIND_ADDRESS_NO_PORT tells
the kernel to choose random port at connect() time instead, when the
full 4-tuple is known.
`g_local_file_fstatat()` needs to fall back to returning an error if
`fstatat()` isn’t defined, which is the case on older versions of macOS
(as well as Windows, which was already handled). Callers shouldn’t call
`g_local_file_fstatat()` in these cases. (That’s already the case.)
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2203
Expose a function that prepares an attribute query string to be passed
to g_file_query_info() to get a list of attributes normally copied with
the file. This function is used by the implementation of
g_file_copy_attributes, and it's useful if one needs to split
g_file_copy_attributes into two stages, for example, when nautilus does
a recursive move of a directory. When files are moved from the source
directory, its modification time changes. To preserve the mtime on the
destination directory, it has to be queried before moving files and set
after doing it, hence these two stages.
Signed-off-by: Maxim Mikityanskiy <maxtram95@gmail.com>
The GSubprocessLauncher class lacks a dispose() method, and frees
all their resources in the finalize() method.
This is a problem with Javascript because the sockets passed to a
child process using g_subprocess_launcher_take_fd() aren't closed
in the parent space until the object is fully freed. This means
that if the child closes a socket, it won't be detected until the
GSubprocessLauncher object has been freed by the garbage
collector.
Just closing the socket externally is not a valid solution,
because the finalize() method will close it again, and since
another file/pipe/socket could have been opened in the meantime
and use the same FD number, the finalize() method would close
an incorrect FD.
An example is launching a child process that uses its own
socket for Wayland: the parent creates two sockets with
socketpair(), passes one to the Wayland API (wl_client_create()),
and the other is passed to the child process using
g_subprocess_launcher_take_fd(). But now there are two instances
of that second socket: one in the parent, and another one in the
child process. That means that, if the child closes its socket (or
dies), the Wayland server will not detect that until the
GSubprocessLauncher object is fully destroyed. That means that a
GSubprocessLauncher created in Javascript will last for several
seconds after the child dies, and every window or graphical element
will remain in the screen until the Garbage Collector destroys the
GSubprocessLauncher object.
This patch fixes this by moving the resource free code into a
dispose() method, which can be called from Javascript. This allows
to ensure that any socket passed to the child with
g_subprocess_launcher_take_fd() can be closed even from Javascript
just by calling the method run_dispose().
Fix https://gitlab.gnome.org/GNOME/glib/-/merge_requests/1670
This combines a massive code re-folding with functionlity expansion
that allows us to track multiple verbs per handler or per application.
Also fixes a few issues and removes a function that made no sense.
Like G_SOURCE_REMOVE and G_SOURCE_CONTINUE, these make it clearer what
it means to return TRUE or FALSE.
In particular, in GDBus methods that fail, the failure case still needs
to return TRUE (unlike the typical GError pattern), leading to comments
like this:
g_dbus_method_invocation_return_error (invocation, ...);
return TRUE; /* handled */
which can now be replaced by:
g_dbus_method_invocation_return_error (invocation, ...);
return G_DUS_METHOD_INVOCATION_HANDLED;
G_DBUS_METHOD_INVOCATION_UNHANDLED is added for symmetry, but is very
rarely (perhaps never?) useful in practice.
Signed-off-by: Simon McVittie <smcv@collabora.com>
The previous parsing code could read off the end of a URI if it had an
incorrect %-escaped character in.
Fix that, and more closely implement parsing for the syntax defined in
RFC 6874, which is the amendment to RFC 3986 which specifies zone ID
syntax.
This requires reworking some network-address tests, which were
previously treating zone IDs incorrectly.
oss-fuzz#23816
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Emptying trash over `gio trash` is a bit slow in comparison to plain
`rm -r`. On my system, it took about 3 min to empty the trash with a
folder containing 600 000 files, which is not ideal as `rm -r` call
took just a few seconds. I found that `g_file_delete` is implemented
differently for locations provided by the trash backend. The trash
backend prevents modifications of trashed content thus the delete
operation is allowed only for the top-level files and folders. So it
is not necessary to recursive delete all files as the permission
denied error is returned anyway. Let's call `g_file_delete` only for
top-level items, which reduces the time necessary for emptying trash
from minutes to seconds...
See: https://gitlab.gnome.org/GNOME/nautilus/-/issues/1589
Some filesystems don't have meaningful access times under at least some
circumstances (see #2189, #2205). In this situation the traditional stat()
and related kernel interfaces have to put something meaningless in the
st_atime field, and have no way to signal that it is meaningless.
However, statx() does have a way to signal that the atime is meaningless:
if the filesystem doesn't provide a useful access time, it will unset
the STATX_ATIME bit (as well as filling in the same meaningless value
for the stx_atime field that stat() would have used, for compatibility).
We don't actually *need* the atime, so never include it in the required
mask. This was already done for one code path in commit 6fc143bb
"gio: Allow no atime from statx" to fix#2189, but other callers were
left unchanged in that commit, and receive the same change here.
It is not actually guaranteed that *any* of the flags in the
returned stx_mask will be set (the only guarantee is that items in
STATX_BASIC_STATS have at least a harmless compatibility value, even if
their corresponding flag is cleared), so it might be better to follow
this up by removing the concept of the required mask entirely. However,
as of Linux 5.8 it looks as though STATX_ATIME is the only flag in
STATX_BASIC_STATS that might be cleared in practice, so this simpler
change fixes the immediate regression.
Resolves: https://gitlab.gnome.org/GNOME/glib/-/issues/2205
Signed-off-by: Simon McVittie <smcv@collabora.com>
It is not allowed to be `NULL` or unset if requested by the file
attribute matcher. Derive it from the basename. This doesn’t handle the
situation of a failed UTF-16 to UTF-8 conversion very well, but will at
least return something.
Note that the `g_filename_display_basename()` function can’t be used as
`GWinHttpFile` provides its URI in UTF-16 rather than in the file system
encoding.
This fixes a crash when using GIMP on Windows. Thanks to lillolollo for
in-depth debugging assistance.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #2194
For interoperability with libdbus, we want to use compatible timeouts.
In particular, this fixes a spurious failure of the `gdbus-server-auth`
test caused by libdbus and gdbus choosing to expire the key (cookie) at
different times, as diagnosed by Thiago Macieira. Previously, the libdbus
client would decline to use keys older than 7 minutes, but the GDBus
server would not generate a new key until the old key was 10 minutes old.
For completeness, also adjust the other arbitrary timeouts in the
DBUS_COOKIE_SHA1 mechanism to be the same as in libdbus. To make it
easier to align with libdbus, create internal macros with the same names
and values used in dbus-keyring.c.
* maximum time a key can be in the future due to clock skew between
systems sharing a home directory
- spec says "a reasonable time in the future"
- was 1 day
- now 5 minutes
- MAX_TIME_TRAVEL_SECONDS
* time to generate a new key if the newest is older
- spec says "If no recent keys remain, the server may generate a new
key", but that isn't practical, because in reality we need a grace
period during which an old key will not be used for new authentication
attempts but old authentication attempts can continue (in practice both
libdbus and GDBus implemented this logic)
- was 10 minutes
- now 5 minutes
- NEW_KEY_TIMEOUT_SECONDS
* time to discard old keys
- spec says "the timeout can be fairly short"
- was 15 minutes
- now 7 minutes
- EXPIRE_KEYS_TIMEOUT_SECONDS
* time allowed for a client using an old key to authenticate, before
that key gets deleted
- was at least 5 minutes
- now at least 2 minutes
- at least (EXPIRE_KEYS_TIMEOUT_SECONDS - NEW_KEY_TIMEOUT_SECONDS)
Based on a merge request by Philip Withnall.
Fixes: #2164
Thanks: Philip Withnall
Thanks: Thiago Macieira
Signed-off-by: Simon McVittie <smcv@collabora.com>
This doesn't trigger the cancellation assertion issue when run locally
(the task didn't return yet, so the error is simply overwritten), but
perhaps it ever does in CI. Anyhow, it's good to have a cancellation
test.
After a splice operation is finished, it attempts to 1) close input/output
streams, as per the given flags, and 2) return the operation result (maybe
an error, too).
However, if the operation gets cancelled early and the streams indirectly
closed, the splice operation will try to close both descriptors and return
on the task when both are already closed. The catch here is that getting the
streams closed under its feet is possible, so the completion callback would
find both streams closed after returning on the first close operation and
return the error, but then the second operation could be able to trigger
a second error which would be returned as well.
What happens here is up to further race conditions, if the task didn't
return yet, the returned error will be simply replaced (but the old one not
freed...), if it did already return, it'll result in:
GLib-GIO-FATAL-CRITICAL: g_task_return_error: assertion '!task->ever_returned' failed
Fix this by flagging the close_async() callbacks, and checking that both
close operations did return, instead of checking that both streams are
closed by who knows.
This error triggers a semi-frequent CI failure in tracker, see the summary at
https://gitlab.gnome.org/GNOME/tracker/-/issues/240
statx does not provide stx_atime when querying a file in a read-only
mounted file system. So call to statx should not expect it to be in
the mask. Otherwise we would fail with ERANGE for querying any file in
a read-only file system.
Fixes#2189.
The `make_pollfd()` call can’t fail because it only does so if
`cancellable == NULL`, and we’ve already checked that. Assert that’s the
case, to shut Coverity up and to catch behavioural changes in future.
Coverity CID: #1159433
Signed-off-by: Philip Withnall <withnall@endlessm.com>
`g_strsplit()` never returns `NULL`, although it can return an empty
strv (i.e. with its first element being `NULL`).
Drop a redundant `NULL` check.
Coverity CID: #1430976
Signed-off-by: Philip Withnall <withnall@endlessm.com>
If `statx()` is supported, query it for the file creation time and use
that if returned.
Incorporating some minor code rearrangement by Philip Withnall
<withnall@endlessm.com>.
Fixes: #1970
This currently just implements the same functionality as the existing
`stat()`/`fstat()`/`fstatat()`/`lstat()` calls, although where a reduced
field set is requested it may return faster.
Helps: #1970
It turns out that our async write operation implementation is broken
on non-O_NONBLOCK pipes, because the default async write
implementation calls write() after poll() said there were some
space. However, the semantics of pipes is that unless O_NONBLOCK is set
then the write *will* block if the passed in write count is larger than
the available space.
This caused a deadlock in https://gitlab.gnome.org/GNOME/glib/-/issues/2182
due to the loop-back of the app stdout to the parent, but even without such
a deadlock it is a problem that we may block the mainloop at all.
In the particular case of g_subprocess_communicate() we have full
control of the pipes after starting the app, so it is safe to enable
O_NONBLOCK (i.e. we can ensure all the code using the fd after this can handle
non-blocking mode).
This fixes https://gitlab.gnome.org/GNOME/glib/-/issues/2182
This has almost the same semantics as WSAECONNRESET and for all
practical purposes is handled the same. The main difference is about
*who* reset the connection: the peer or something in the network.
For UDP sockets this happens when receiving packets and previously sent
packets returned an ICMP "Time(-to-live) expired" message. This is
similar to WSAECONNRESET, which on UDP sockets happens when receiving
packets and previously sent packets returned an ICMP "Port Unreachable"
message.
This is a step towards supporting `statx()`, which allows the set of
fields it returns to be specified by the caller. Currently, the existing
`stat()` and `fstat()` calls continue to be made, and there are no
behavioural changes — but the new wrapper functions will be extended in
future.
Helps: #1970
Don’t call `g_file_query_exists()` followed by `g_file_delete()`. Just
call `g_file_delete()` and check the error.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Make `G_URI_FLAGS_PARSE_RELAXED` available instead, for the
implementations which need to handle user-provided or incorrect URIs.
The default should nudge people towards being compliant with RFC 3986.
This required also adding a new `G_URI_PARAMS_PARSE_RELAXED` flag, as
previously parsing param strings *always* used relaxed mode and there
was no way to control it. Now it defaults to using strict mode, and the
new flag allows for relaxed mode to be enabled if needed.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #2149
Add support for x-gvfs-notrash mount option, which allows to disable
trash functionality for certain mounts. This might be especially useful
e.g. to prevent trash folder creation on enterprise shares, which are
also accessed from Windows...
https://bugzilla.redhat.com/show_bug.cgi?id=1096200
There is already g_unix_mount_at function which allows to find certain
unix mount for given mount path. It would be useful to have similar
function for mount points, which will allow to replace custom codes in
gvfs. Let's add g_unix_mount_point_at.
_g_uri_parse_authority() can be replaced with g_uri_split_network() &
PARSE_STRICT. Keep the original error code, for compatibility reasons.
Notice that GUri uses gint for the port, and value -1 if the port value
is missing. However, GNetworkAddress::port is a guint.
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
_g_uri_parse_authority() without argument is actually checking that the
URI is valid, by checking it parses successfully
We keep the existing error domain / code for compatibility reasons,
instead of raising the underlying G_URI_ERROR.
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
_g_uri_from_authority() is doing the same work as g_uri_join(): taking
URI components and merging them in a legit URI string, with encoding.
It turns out g_uri_from_authority was unnecessarily complex, since no
caller used the userinfo field.
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
It may be defined by the environment (we document that as being allowed)
— if so, individual files should not try to redefine it, as that causes
a preprocessor warning.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Where applicable. Where the current use of `g_file_set_contents()` seems
the most appropriate, leave that in place.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1302
Give GAppInfo a bunch of readonly properties, and
support them in GDesktopAppInfo. This makes app infos
more convenient to work with in GTK4, and in general.
g_task_set_name() was added in GLib 2.60, so only use it in the
overridden definition of g_task_set_source_tag() if the user has said
that they require GLib ≥ 2.60.
This is a follow up to commit b08bd04abe.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
There is no guarantee that this function would not be called
concurrently. Particularly since flatpak_info_read was set to TRUE
before /.flatpak-info is actually read from disk, there is a potential
race where a second thread would return default values for the various
flags set from that file.
Fixes#2159
Correct an off-by-one error in hex_unescape_string()'s computation of
the output string length.
(Turned into a git-format patch by Philip Withnall. Original patch
submitted on the Debian bug tracker, bug#962912.)
It's safe to assume an escaped string doesn't contain embedded null bytes,
but raw memory buffers (as returned by getxattr()) require more care.
If the length of the data to be escaped is known, use that knowledge instead
of invoking strlen().
(Turned into a git-format patch by Philip Withnall. One minor formatting
tweak. Original patch submitted on the Debian bug tracker, bug#962912.)
Fixes: #422
And improve them externally, where not otherwise set, by setting them
from the function name passed to `g_task_set_source_tag()`, if called by
third party code.
This should make profiling and debug output from GLib more useful.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
`complete_in_idle_cb()` shows up in a lot of sysprof traces, so it’s
quite useful to include the most specific contextual information we can
in it.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
When an app is spawned using g_desktop_app_info_launch_uris_with_spawn
it will expand the various token in the app's commandline with the
URIs of the files to open. The expand_macro() function that is used for
this advances the pointer to the URI list to show up to which entries
it used.
To not loose the pointer to the list head a duplicate of the URI list
was actually passed to expand_macro(). However, it's not necessary to
create a copy of the URI list for that as expand_macro() will only
change which element the pointer will point to.
This behaviour actually caused the duplicated list to be leaked as the
the list pointer is NULL once all URIs are used up by expand_macro()
and thus nothing was freed at the end of the function.
In ostree based systems, such as flatpak and fedora silverblue, the
time of modification of every system file is epoch 0, including
giomodule.cache, which means that every module is loaded and unloaded
every time.
The solution is to use the change time of the file as well. In a typical
system, it is equal to the mtime, and in an ostree based system, since
the directory is mounted as read-only, the user cannot add a module and
we must assume that the cache file corresponds to the modules.
* Add g_tls_connection_get_channel_binding_data API call
* Add g_dtls_connection_get_channel_binding_data API call
* Add get_binding_data method to GTlsConnection class
* Add get_binding_data method to GDtlsConnection interface
* Add GTlsChannelBindingType enum with tls-unique and
tls-server-end-point types
* Add GTlsChannelBindingError enum and G_TLS_CHANNEL_BINDING_ERROR
quark
* Add new API calls to documentation reference gio-sections-common
This speeds up the `cancellable` test a little by stopping waiting for
the threads to start up as soon as they have started, rather than after
an arbitrary timeout.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1764
This should fix some sporadic test failures in this test, although I
can’t be sure as I was unable to reproduce the original failure.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Closes: #1764
It seems that allowing the GCancellable to be finalised in either the
main thread or the worker thread sometimes leads to crashes when running
on CI.
I cannot reproduce these crashes locally, and various analyses with
memcheck, drd and helgrind have failed to give any clues.
Fix this for this particular test case by deferring destruction of the
`GCancellable` instances until after the worker thread has joined.
That’s OK because this test is specifically checking a race between
`g_cancellable_cancel()` and disposal of a `GCancellableSource`.
The underlying bug remains unfixed, though, and I can only hope that we
eventually find a reliable way of reproducing it so it can be analysed
and fixed.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
The G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE is set to TRUE only for NFS
filesystem types currently. Let's add also SMB filesystem types. This
also changes g_local_file_is_nfs_home function logic to handle only
NFS filesystems.
The g_local_file_is_remote function is misleading as it works only for
NFS filesystem types and only for locations in home directorly. Let's
rename it to g_local_file_is_nfs_home to make it obvious.
statfs/statvfs is called several times when querying filesystem info.
This is because the G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE attribute is set
over is_remote_fs function, which calls statfs/statvfs again. Let's use
the already known fstype instead of redundant statfs/statvfs calls.
This also changes g_local_file_is_remote implementation to use
g_local_file_query_filesystem_info to obtain fstype, which allows to
remove duplicated code from is_remote_fs function.
The G_FILE_ATTRIBUTE_FILESYSTEM_REMOTE currently works only for locations
in the home directory. Let's make it work also for files outside the home
directory.
There are glocalfile.h and glocalfileprivate.h header files currently.
None of those header files is public, so it doesn't make sense to have
two private headers for glocalfile.c. Let's remove glocalfileprivate.h.
This was mostly machine generated with the following command:
```
codespell \
--builtin clear,rare,usage \
--skip './po/*' --skip './.git/*' --skip './NEWS*' \
--write-changes .
```
using the latest git version of `codespell` as per [these
instructions](https://github.com/codespell-project/codespell#user-content-updating).
Then I manually checked each change using `git add -p`, made a few
manual fixups and dropped a load of incorrect changes.
There are still some outdated or loaded terms used in GLib, mostly to do
with git branch terminology. They will need to be changed later as part
of a wider migration of git terminology.
If I’ve missed anything, please file an issue!
Signed-off-by: Philip Withnall <withnall@endlessm.com>
In glib-networking#127, it was reported that we don't properly implement
the documented behavior of these properties. However, we cannot fix it
because libsoup relies on the implemented behavior, and it's hard to
change that without cascading breakage. The practical solution is to
adjust our documentation to match reality. There should be no downsides
to this, and compat risk of changing the documentation is much smaller
than risk of changing the implementation, so I think this is the best we
can make of an unfortunate situation. See glib-networking#127 for full
discussion and glib-networking#129 for the regression when we attempted
to match the documented behavior.
Some editors automatically remove trailing blank lines, or
automatically add a trailing newline to avoid having a trailing
non-blank line that is not terminated by a newline. To avoid unrelated
whitespace changes when users of such editors contribute to GLib,
let's pre-emptively normalize all files.
Unlike more intrusive whitespace normalization like removing trailing
whitespace from each line, this seems unlikely to cause significant
issues with cherry-picking changes to stable branches.
Implemented by:
find . -name '*.[ch]' -print0 | \
xargs -0 perl -0777 -p -i -e 's/\n+\z//g; s/\z/\n/g'
Signed-off-by: Simon McVittie <smcv@collabora.com>
While these assertions look right at the first glance,
they actually crash the program. That's because GObject
insists on initializing all construct-only properties
to their default values, which results in
g_win32_registry_key_set_property() being called multiple
times with NULL string, once for each unset property.
If "path" is actually set by the caller, a subsequent
call to set "path-utf16" to NULL will fail an assertion,
since absolute_path is already non-NULL.
With assertions moved the set-to-NULL calls bail out before
an assertion is made.
This ensures that we do really export the symbols for Visual
Studio-style builds, by using _GLIB_EXTERN to decorate the generated
prototypes and including config.h so that we are sure the symbols are
actually exported.
This adds three options to gdbus-codegen so that we may be able to
use a self-defined symbol decorator, such as _GLIB_EXTERN, to decorate
the generated prototypes, to be used possibly to export the symbols, if
needed.
The other two options allows including headers that are required for the
specified symbol decorator to be usable and preprocessor macros that are
required for the symbol decorator to be defined appropriately, also when
needed.
Have the generated .c code decorate the prototypes with "G_MODULE_EXPORT"
instead of "extern" when --internal is not being used, so that we also
export the symbols from the generated code on Visual Studio-style
compilers. If --internal is used, we decorate the prototypes with
"G_GNUC_INTERNAL", as we did before.
Note that since the generated .c code does not attempt to include the
generated headers (if one is also generated), the gnerated headers are
still generated as they were before.
Sometimes this test was timing out due to the file monitor notifications
taking longer than the arbitrary 2s delay before ending the test and
checking its results at the end of `iclosed_cb()`.
Avoid that timing-dependence by ending the test when the expected file
monitor notifications are seen, or after a 10s timeout (if so, the test
is failed).
This makes the test run 4× faster in the normal case, as it’s no longer
waiting for a timeout to elapse if the file monitor notifications come
in sooner.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
The test added for #1841 spawned 100000 threads. That was fine on a
desktop machine, but on a heavily loaded CI machine, it could result in
large (and unpredictable) slowdowns, resulting in the test taking over
120s in about 1 in 5 runs, and hence failing that CI pipeline due to a
timeout. When passing normally on CI, the test would take around 90s.
Here’s a histogram of time per iteration on a failing (timed out) test
run. Each iteration is one thread spawn:
Iteration duration (µs) | Frequency
------------------------+----------
≤100 | 0
100–200 | 30257
200–400 | 13696
400–800 | 1046
800–1000 | 123
1000–2000 | 583
2000–4000 | 3779
4000–8000 | 4972
8000–10000 | 1027
10000–20000 | 2610
20000–40000 | 650
40000–80000 | 86
80000–100000 | 10
100000–200000 | 2
>200000 | 0
There’s no actual need for the test to spawn 100000 threads, so rewrite
it to reuse a single thread, and pass new data to that thread.
Reverting the original commit (e4a690f5dd) reproduces the failure on
100 out of 100 test runs with this commit applied, so the test still
works.
The test now takes 3s, rather than 11s, to run on my computer, and has
passed when run with `meson test --repeat 1000 cancellable`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
An extra argument to g_win32_registry_key_get_value_w() and
g_win32_registry_key_get_value() indicates that RegLoadMUIStringW()
should be used instead of RegQueryValueExW(). It only works on
strings, and automatically resolves resource strings (the ones
that start with "@").
The extra argument is needed to find resource DLLs that are only
specified by their relative name.
It is critical to mention how the identity parameter is expected to be
handled. In particular, if identity is not passed, then the identity of
the server certificate will not be checked at all. This is in contrast
to the connection-level APIs, which are supposed to be fail-safe. The
database and certificate-level APIs are more manual.
There’s no need to call `access()` and then `stat()` on the keyring
directory to check that it exists, is a directory, and has the right
permissions. Just call `stat()`.
This eliminates one potential TOCTTOU race in this code.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1954
There was a time-of-check-to-time-of-use (TOCTTOU) race in the keyring
lock code, where it would check the existence of the lock file using
`access()`, then proceed to call `open(O_CREAT | O_EXCL)` to try and
create the lock file once `access()` showed that it didn’t exist.
The problem is that, because this is happening in a shared directory
(`~/.dbus-keyrings`), another process could quite legitimately create
the lock file in the meantime.
Instead, unconditionally call `open()` and ignore errors from it (which
will be returned if the lock file already exists) until it succeeds (or
the code times out).
This eliminates the TOCTTOU race, and simplifies the timeout behaviour
so there aren’t two loops (check for existence, try to create)
happening. It brings this code in line with what dbus.git does (see
`_dbus_keyring_lock()`).
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1954
When multiple tests were run in parallel, this would race on its access
to `~/.dbus-keyrings` to authenticate with the D-Bus server, since the
keyring directory was not appropriately sandboxed to the unit test.
Use `G_TEST_OPTION_ISOLATE_DIRS` to automatically isolate each unit
test’s directory usage.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1954
Commit 721e385 left one remaining race in the filter test, with a
comment associated with it. Unfortunately, the (seemingly unrelated)
changes in #1841 to `GCancellable` seem to have made this remaining race
a lot more likely to fail on FreeBSD than before.
What’s likely to have happened (although I was unable to reproduce the
failure, due to not having a FreeBSD system; I was only able to
reproduce the problem as a 3/1000 failure on Linux, which is still worth
fixing) is that the atomic write of the `FilterData.serial` to be
expected by the filter function sometimes happened after the filter
function had executed, so the expected message was dropped and didn’t
result in an update to the `FilterData` state.
Rework the test so that instead of setting some expectations (on
`FilterData`) in one thread and then checking them in another thread,
the worker thread just unconditionally returns messages from the filter
function to the main thread, and then the main thread checks whether the
expected one has been filtered.
With this change applied, the `gdbus-connection` test passes 5000 times
in a row for me, on Linux; and doesn’t seem to fail any more on the
FreeBSD CI machines over a few runs. (Previously it failed on 4/5 runs.)
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #2092Fixes: #1957
Mention in the documentation that (presumably for performance reasons)
the search results from `g_desktop_app_info_search()` are not filtered
by executable presence or hidden attribute.
Perhaps they should be in future, but for now we should at least
document it.
Spotted by Will Thompson.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
By default, meson builds glib with -Werror=format=2, which
implies -Werror=format-nonliteral. With these flags, clang errors
out on e.g. the g_message_win32_error function, due to "format
string is not a string literal". This function takes a format
string, and passes the va_list of the arguments onwards to
g_strdup_vprintf, which is annotated with printf attributes.
When passing a string+va_list to another function, GCC doesn't warn
with -Wformat-nonliteral. Clang however does warn, unless the
functions themselves (g_message_win32_error and set_error) are decorated
with similar printf attributes (to force the same checks upon the
caller) - see
https://clang.llvm.org/docs/AttributeReference.html#format
for reference.
Adding these attributes revealed one existing mismatched format string
(fixed in the preceding commit).
The GIO tests memory-monitor-dbus and memory-monitor-portal use a number
of third party Python modules that may not be present when running the
test case.
Instead of failing due to missing imports, catch the ImportError and
mock a test case that skips. This can't use the usual unittest.skip
logic because the test case class itself uses a 3rd party module.
Closes#2083.
There are two memory monitor tests that use Python's unittest module directly,
but GLib tests should be outputting TAP. Use the embedded TAPTestRunner to
ensure that TAP is output for these tests too.
The G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE attribute doesn't have to be
always set. See https://gitlab.gnome.org/GNOME/gvfs/-/merge_requests/68
for more details. In that case, the g_file_query_default_handler function
fails with the "No application is registered as handling this file" error.
Let's fallback to the "standard::fast-content-type" attribute instead to
fix issues when opening such files.
https://gitlab.gnome.org/GNOME/nautilus/-/issues/1425
Meson 0.54.0 added a new method meson.override_dependency() that must be
used to ensure dependency consistency. This patch ensures a project that
depends on glib will never link to a mix of system and subproject
libraries. It would happen in such cases:
The system has glib 2.40 installed, and a project does:
dependency('glib-2.0', version: '>=2.60',
fallback: ['glib', 'glib_dep'])
dependency('gobject-2.0')
The first call will configure glib subproject because the system libglib
is too old, but the 2nd call will return system libgobject.
By overriding 'gobject-2.0' dependency while configuring glib subproject
during the first call, meson knows that on the 2nd call it must return
the subproject dependency instead of system dependency.
This also has the nice side effect that with Meson >0.54.0 an
application depending on glib can declare the fallback without knowing
the dependency variable name: dependency('glib-2.0', fallback: 'glib').
Slightly unexpectedly, `g_icon_serialize()` doesn’t produce a floating
`GVariant`, it produces one with full ownership and returns that. That’s
not the convention for `GVariant` return values from functions which
build variants, but there’s nothing we can do to change this now as that
would be an API break.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
D-Bus filter functions run in a worker thread. The `gdbus-connection`
test was sharing a `FilterData` struct between the main thread and the
filter function, which was occasionally (on the order of 0.01% of test
runs) causing spurious test failures due to racing on reads/writes of
`num_handled`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #480
g_assert() can be compiled out with G_DISABLE_ASSERT, which renders the
test rather useless.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #480
If a username and password are specified by the caller, `GSocks5Proxy`
tells the server that it supports anonymous *and* username/password
authentication, and the server can choose which it prefers.
Otherwise, `GSocks5Proxy` only says that it supports anonymous
authentication. If that’s not acceptable to the server, the code was
previously returning `G_IO_ERROR_PROXY_AUTH_FAILED`. That error code
doesn’t indicate to the caller that authentication might succeed were
they to provide a username and password.
Change the error handling to make that clearer. A fuller solution would
be to expose more of the method negotiation in the `GSocks5Proxy` API,
so that the caller can specify ahead of time which authentication
methods they want to use. That can follow in issue #2059 though.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1988
They were not actually asynchronous, and hence caused blocking in the
main thread. Deleting them means the default implementation of those
vfuncs is used, which runs the sync implementation in a thread — which
is what is wanted here.
Spotted by Benjamin Otte.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #2051
There’s a minor race condition between cancellation of a `GCancellable`,
and disposal/finalisation of a `GCancellableSource` in another thread.
Thread A Thread B
g_cancellable_cancel(C)
→cancellable_source_cancelled(C, S)
g_source_unref(S)
cancellable_source_dispose(S)
→→g_source_ref(S)
→→# S is invalid at this point; crash
Thankfully, the `GCancellable` sets `cancelled_running` while it’s
emitting the `cancelled` signal, so if `cancellable_source_dispose()` is
called while that’s high, we know that the thread which is doing the
cancellation has already started (or is committed to starting) calling
`cancellable_source_cancelled()`.
Fix the race by resurrecting the `GCancellableSource` in
`cancellable_source_dispose()`, and signalling this using
`GCancellableSource.resurrected_during_cancellation`. Check for that
flag in `cancellable_source_cancelled()` and ignore cancellation if it’s
set.
The modifications to `resurrected_during_cancellation` and the
cancellable source’s refcount have to be done with `cancellable_mutex`
held so that they are seen atomically by each thread. This should not
affect performance too much, as it only happens during cancellation or
disposal of a `GCancellableSource`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1841
`g_assert()` is compiled out if `G_DISABLE_ASSERT` is defined, and
`g_assert_*()` gives more detailed failure messages.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Guard against NULL type being passed to
g_content_type_get_generic_icon_name() just as we protect
g_content_type_get_description(), otherwise it will cause a crash.
See https://gitlab.gnome.org/GNOME/gtk/issues/2482
Distributions will likely want to update GLib before
GObject-Introspection, to avoid circular dependencies.
Signed-off-by: Simon McVittie <smcv@debian.org>
It was checking for the main SOCKS5 version number, rather than the
subnegotiation version number. The username/password authentication
protocol is described in https://tools.ietf.org/html/rfc1929.
Spotted and diagnosed by lovetox.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1986
Clang warns about string+int not appending to the string (to try and
catch newbie mistakes). While this test didn’t expect that to happen, it
was substituting the same constant string in multiple places for no good
reason. Switch to a single static const string, which should also fix
the compiler warning.
We have to define the string length since it’s used in various
stack-allocated array lengths. This is the easiest fix without more
major refactoring of the test to be less 90s.
Also make things a bit more static.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
When running under CI, each iteration takes so long that the total test
time is around 200s. If the CI runner is highly loaded, this can tip it
over the timeout of 360s.
Reduce the iteration counts unless running the test thoroughly.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1515
Currently the test waits for 1s before deciding that a refcount has been
leaked. But slow test machines might take longer than that between
scheduling different threads to sort out the refcount, so increase the
timeout.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1515
Previously, if the `--address` option was passed to `gdbus-tool`, it
would treat the connection as peer to peer. However, almost all the
commands `gdbus-tool` supports require a message bus (introspection,
calling a method with a destination, etc.). Only the `signal` command
would ever work on a peer-to-peer connection (if no `--dest` was
specified).
So change the `--address` option to generally create message bus
connections.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #938
bindfs is part of the setup process, so if it fails (as can happen if
the `fuse` kernel module has not been loaded — not much we can do about
that) then skip the test.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Add a note to the documentation of
`g_dbus_connection_signal_unsubscribe()`, `g_bus_unwatch_name()` and
`g_bus_unown_name()` warning about the need to continue iterating the
caller’s thread-default `GMainContext` until the
unsubscribe/unwatch/unown operation is complete.
See the previous few commits and #1515 for an idea of the insidious bugs
that can be caused by not iterating the `GMainContext` until
everything’s synchronised.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
When testing that signals are delivered to the correct thread, and are
delivered the correct number of times, call `EmitSignal()` on the
`gdbus-testserver` to trigger a signal emission, and listen for that.
Previously, the code listened for `NameOwnerChanged` and connected to
the bus again to trigger emission of that. The problem with that is that
other things happening on the bus (for example, an old
`gdbus-testserver` instance disconnecting) can cause `NameOwnerChanged`
signal emissions. Sometimes, the `gdbus-threading` test was failing the
`signal_count == 1` assertion due to receiving more than one
`NameOwnerChanged` emission.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1515
This is equivalent, but makes the loop exit conditions a little clearer,
since they’re actually in a `while` statement, rather than being a
`g_main_loop_quit()` call in a callback somewhere else in the file.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1515
As with the previous commit, don’t stop iterating the `context` in
`test_delivery_in_thread_func()` until the unsubscription from a signal
is complete, and hence there’s a guarantee that no callbacks are pending
in the `thread_context`.
This commit uses the `GDestroyNotify` for
`g_dbus_connection_signal_subscribe()` as a synchronisation message from
the D-Bus worker thread to the `test_delivery_in_thread_func()` thread
to notify of signal unsubscription.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1515
Previously, the code in `ensure_gdbus_testserver_up()` created a proxy
object and watched its `name-owner` to see when the
`com.example.TestService` name appeared.
This ended up subscribing to three signals (one of them for name
ownership, and two unused for properties of the proxy), and was racy. In
particular, the `name-owner` property could be set before all D-Bus
messages had been processed — it could have been derived from getting
the owner of the name, for example.
This left unprocessed messages hanging around in the `context`, but that
context was never iterated again, which essentially leaked the
references held by those messages. That included a reference to the
`GDBusConnection`.
The first part of the fix is to simplify the code to use
`g_bus_watch_name_on_connection()`, so there’s only one signal
subscription to worry about.
The second part of the fix is to use the `GDestroyNotify` callback for
the watch data to be notified of when all D-Bus traffic has been
processed and the signal unsubscription is complete. At this point, it’s
guaranteed that there are no idle callbacks pending in the
`GMainContext`, since the `GDestroyNotify` callback is the last one
invoked on the `GMainContext`.
Essentially, this commit uses the `GDestroyNotify` callback as a
synchronisation message between the D-Bus worker thread and the thread
calling `ensure_gdbus_testserver_up()`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1515
Iterate the given `context` while waiting, rather than sleeping. This
ensures that if the errant `GDBusConnection` ref is held by some pending
callback in the given `context`, it will actually be released.
Typically `context` is going to be the global default main context.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1515
This introduces no functional changes, but makes the code a little more
explicit about which connection and main context it’s operating on.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1515
`CallDestroyNotifyData` never uses that `GMainContext`, and holding a
ref to it could cause reference count cycles if the `GMainContext` is no
longer being iterated.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1515
The fix for bgo#651133 (commit 7e0f890e38) introduced a kind of weak
ref, which had to be thread-safe due to the fact that `GDBusProxy`
operates in one thread but can emit signals in another.
Since that commit, `GWeakRef` was added, which does the same thing. Drop
the custom code in favour of it; this should be functionally equivalent,
but using an RW lock rather than a basic mutex, which should reduce
contention.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
These checks used to be a precondition on test_threaded_singleton(); but
the earlier tests could leave the refcount of the shared connection in a
bad state, and this wouldn’t be caught until later.
Factor out the check, increase the iteration count to 1000 (so the check
blocks for up to 1s rather than 100ms), and call it in more places.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
https://gitlab.gnome.org/GNOME/glib/issues/1515
g_assert() can be compiled out with G_DISABLE_ASSERT, which renders the
test rather useless.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
https://gitlab.gnome.org/GNOME/glib/issues/1515
mtab_file_changed_id is not currently removed when finalizing, which
could potentially lead to segfaults. Let's remove the source when
finalizing to avoid this.
mtab_file_changed_id might be set on thread default context, but it is
always cleared on the global context because of usage of g_idle_add. This
can cause the emission of redundant "mounts-change" signals. This should
not cause any issues to the client application, but let's attach the idle
source to the thread-default context instead to avoid those races for sure.
The `get_mounts_timestamp()` function uses `mount_poller_time` when
`proc_mounts_watch_source` is set, but the `mount_poller_time` is not
initialized in the same time as `proc_mounts_watch_source`. This may
cause that zero, or some outdated value is returned. Let's initialize
`mount_poller_time` to prevent invalid values to be returned.
The Nautilus test suite often crashes with "GLib-FATAL-CRITICAL:
g_source_is_destroyed: assertion 'g_atomic_int_get (&source->ref_count)
> 0' failed" if it is started with "GIO_USE_VOLUME_MONITOR=unix". This
is because GUnixMountMonitor is simultaneously used from multiple
threads over GLocalFile and GVolumeMonitor APIs. Let's add guards for
proc_mounts_watch_source and mount_poller_time variables to prevent
those crashes.
Fixes: https://gitlab.gnome.org/GNOME/glib/issues/2030
There was a slight race in name ownership: a gap between calling
`RequestName` (or receiving its reply) and subscribing to `NameLost`. In
that gap, another process could request and receive the name, and this
one wouldn’t know about it.
Fix that by subscribing to `NameAcquired` and `NameLost` before calling
`RequestName`, and then unsubscribing again if the subscriptions turn
out not to be necessary (if the process can’t own the requested name).
Spotted and diagnosed by Miika Karanki.
One of the tests needs an additional iteration of the main loop in order
to free all the signal closures before it can complete its checks.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1517
This is a fairly large refactoring. The highlights are:
- Removing in-progress connections/addresses from GSocketClientAsyncConnectData:
This caused issues where multiple ConnectionAttempt's would step over eachother
and modify shared state causing bugs like accidentally bypassing a set proxy.
Fixes#1871Fixes#1989Fixes#1902
- Cancelling address enumeration on error/completion
- Queuing successful TCP connections and doing application layer work serially:
This is more in the spirit of Happy Eyeballs but it also greatly simplifies
the flow of connection handling so fewer tasks are happening in parallel
when they don't need to be.
The behavior also should more closely match that of g_socket_client_connect().
- Better track the state of address enumeration:
Previously we were over eager to treat enumeration finishing as an error.
Fixes#1872
See also #1982
- Add more detailed documentation and logging.
Closes#1995
There were some problems about where to install `gio-launch-desktop` to
support multiarch systems without circular dependencies. Simon McVittie
suggested that, actually, given the current set of platforms supported
by `GDesktopAppInfo` (they’re all POSIX), we could just use `sh`.
That simplifies things nicely. `gio-launch-desktop` can always be
resurrected (and the multiarch debate continued and resolved) if needed
in future.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1633
Some CI platforms invoke these tests with euid != 0 but with
capabilities. Detect whether we have Linux CAP_DAC_OVERRIDE or other
OSs' equivalents, and skip tests that rely on DAC permissions being
denied if we do have that privilege.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Fixes: https://gitlab.gnome.org/GNOME/glib/issues/2027
Fixes: https://gitlab.gnome.org/GNOME/glib/issues/2028
There were a couple of custom paths which could end up being relative,
rather than absolute, due to not properly prefixing them with
`get_option('prefix')`.
The use of `join_paths()` here correctly drops all path components
before the final absolute path in the list of arguments. So if someone
configures GLib with an absolute path for `gio_module_dir`, that will be
used unprefixed; but if someone configures with a relative path, it will
be prefixed by `get_option('prefix)`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1919
The loops should continue iterating if the timeout is non-zero and we're
still waiting for the updated value. Otherwise, if things break, we'll
be waiting until we receive a value that never arrives.
"gio info" output doesn't contain any information about mount points, but
that information can be useful when debugging issues in facilities that
depend on knowing about mount points, such as the trash API.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Co-authored-by: Ondrej Holy <oholy@redhat.com>
Documentation says that g_file_peek_path() returns exactly the same
what g_file_get_path(), but this is not true. Apart from that the code
segfaults for some uris (e.g. for "trash:///"), it returns target-uri
for trash and recent schemes. This is unexpected and can lead to various
issues among others because the target-uri paths are not automatically
translated back to GDaemonFile as it is done with gvfsd-fuse paths.
g_file_get_path() returns NULL for trash and recent schemes, because
fuse paths are not provided for those schemes. So g_file_peek_path()
should return NULL as well. It is up to the concrete application to
use target-uri when appropriate.
This change was made as a part of commit 4808a957, however, neither
the commit message, neither the corresponding bug doesn't mention this
crucial change and doesn't give any clear reasoning. So let's revert
this.
The GMemoryMonitor interface uses G_DECLARE_INTERFACE, which provides a
typedef for the interface dummy type. We declare the same type inside
the global giotypes.h header, which leads to typedef redeclaration
warnings on toolchains that do not support—intentionally or not—the C11
feature of typedef redefinition.
While we do have a toolchain requirement for C11 typedef redefinitions
listed on our wiki, we also suspended it temporarily to allow users of
non-C11 compilers to work on newer versions of GLib; so, let's keep them
working a while longer.
Python tuple comparisons actually do what we want for comparing major
and minor versions, so tidy things up by using that.
This introduces no functional changes.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
This reverts commit b6d8efbebc.
This GLib API is good, but the implentation is not ready, so there's no
reason to commit to the API in GLib 2.64. We can reland again when the
implementation is ready.
There are three problems: (a) The glib-networking implementation normally
works, but the test has been broken for a long time. I'm not comfortable
with adding a major new feature without a working test. This is
glib-networking#104. (b) The WebKit implementation never landed. There
is a working patch, but it hasn't been accepted upstream yet. This API
isn't needed in GLib until WebKit is ready to start using it.
https://bugs.webkit.org/show_bug.cgi?id=200805. (c) Similarly, even if
the WebKit API was ready, that itself isn't useful until an application
is ready to start using it, and the Epiphany level work never happened.
Let's try again for GLib 2.66. Reverting this commit now just means we
gain another six months before committing to the API forever. No reason
to keep this in GLib 2.64 when nothing is using it yet.
Since we (optionally) require nanosecond precision for this
(utimes() is used on *nix), use SetFileTime(), which nominally
has 100ns granularity (actual filesystem might be coarser), instead of
g_utime (), which only has 1-second granularity.
Expand our private statbuf structure with st_mtim, st_atim and st_ctim
fields, which are structs that contain tv_sec and tv_nsec fields,
representing a timestamp with 1-second precision (same value as st_mtime, st_atime
and st_ctime) and a fraction of a second (in nanoseconds) that adds nanosecond
precision to the timestamp.
Because FILEETIME only has 100ns precision, this won't be very precise,
but it's better than nothing.
The private _g_win32_filetime_to_unix_time() function is modified
to also return the nanoseconds-remainder along with the seconds timestamp.
The timestamp struct that we're using is named gtimespec to ensure that
it doesn't clash with any existing timespec structs (MinGW-w64 has one,
MSVC doesn't).
This avoids a crash when starting Evolution, and fixes the
network-monitor and network-monitor-race test cases on my developer
workstation. (I assume the CI is not crashing due to lack of network
access there.)
Problem is that if a network already exists in the networks table,
g_hash_table_add() "destroys" (unrefs) it before adding the new one
(which we failed to ref before adding). This means we just accidentally
lost a ref. In practice, the network gets unexpectedly destroyed here
before returning.
Fixes#2020
This complements the `--glib-min-required` argument, just like the
`GLIB_MIN_REQUIRED` and `GLIB_MAX_ALLOWED` preprocessor defines which
control access to APIs in C.
Currently, it doesn’t affect code generation at all. When we next change
code generation, we will need to gate any new API usage on this
argument.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1993
This makes it consistent with the `GLIB_MIN_REQUIRED` defines which are
used for API stability/versioning in C code.
It doesn’t otherwise change the behaviour of the `--glib-min-version`
argument.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1993
Rather than using an array, which requires a lot of iteration over it to
check whether a particular network is present. Using a hash table only
requires iteration in the can_reach() case, where we need to match a
mask in the networks array, rather than equal it.
This should improve performance for large numbers of routes.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1925
Following on from #978, it seems that #1232 is another instance of the
same problem: signals emitted across threads can’t guarantee their user
data is kept alive between committing to emitting the signal and
actually invoking the callback in the relevant thread.
Fix that by using weak refs to the `GDBusObjectManagerClient` as the
user data for its signals, rather than no refs. Strong refs would create
an unbreakable reference count cycle.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1232
It’s possible for `g_bus_unwatch_name()` to be called after a
name-appeared or name-vanished handler has been scheduled to be called
in another thread, but before that callback is actually invoked. If so,
the subscribing thread will receive a callback after it’s called
`g_bus_unwatch_name()`, which is unexpected and could cause bugs.
Double-check `client->cancelled` in the target thread before actually
invoking the callback.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #604
This fixes the following build failure on FreeBSD:
```
In file included from ../gio/tests/win32-appinfo.c:24:
/usr/include/malloc.h:3:2: error: "<malloc.h> has been replaced by <stdlib.h>"
#error "<malloc.h> has been replaced by <stdlib.h>"
```
Hopefully it doesn’t break Windows.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
As with all D-Bus signal subscriptions, it’s possible for a signal
callback to be invoked in one thread (T1) while another thread (T2) is
unsubscribing from that signal. In this case, T1 is the main thread, and
T2 is the D-Bus connection worker thread which is unsubscribing all
signals as it’s in the process of closing.
Due to this possibility, all `user_data` for signal callbacks needs to
be referenced outside the lifecycle of the code which
subscribes/unsubscribes the signal. In other words, it’s not safe to
subscribe to a signal, store the subscription ID in a struct,
unsubscribe from the signal when freeing the struct, and dereference the
struct in the signal callback. The data passed to the signal callback
has to have its own strong reference.
Instead, it’s safe to subscribe to a signal and add a strong reference
to the struct, store the subscription ID in that struct, and unsubscribe
from the signal when the last external reference to your struct is
dropped. That unsubscription should break the refcount cycle between the
signal connection and the struct, and allow the struct to be completely
freed. Only with that approach is it safe to dereference the struct in
the signal callback, if there’s any possibility that the signal might be
unsubscribed from a separate thread.
The tests need specific additional main loop cycles to completely emit
the NameLost signal callback. Ideally they need refactoring, but this
will do (1000 test cycles passed).
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #978
This just removes a now-redundant intermediate array. This means that
the `SignalSubscriber` instances are now potentially freed a little
sooner, inside the locked segment, but they are already careful to only
call their `user_data_free_func` in the right thread. So that should not
deadlock.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #978
Instead of storing a copy of the `callback` and `user_data` from a
`SignalSubscriber` in a `SignalInstance` struct (which is the closure
for signal callback data as it’s sent from the D-Bus worker thread to
the thread which originally subscribed to a signal), store a strong
reference to the `SignalSubscriber` struct itself.
This keeps the `SignalSubscriber` alive until the emission is
complete, which ensures that the `user_data` is not freed prematurely.
It also slightly reduces the allocation size of `SignalInstance` (not
that it matters).
This is threadsafe because the fields in `SignalSubscriber` are all
immutable after construction.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #978
Tie the destruction of the `user_data` to the destruction of the
`SignalSubscriber` struct. This is tidier, and ensures that the fields
in `SignalSubscriber` are all immutable after being set, so the
structure can safely be used across threads without locking.
It doesn’t matter which thread we call `call_destroy_notify()` in, since
it always defers calling `user_data_free_func` to the user-provided
`GMainContext`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #978
The `SignalSubscriber` structs contain the callback and `user_data` of each
subscriber to a signal, along with the `guint id` token held by that
subscriber to identify their subscription. There are one or more
`SignalSubscriber` structs for a given signal match rule, which is
represented as a `SignalData` struct.
Previously, the `SignalSubscriber` structs were stored in a `GArray` in
the `SignalData` struct, to reduce the number of allocations needed
when subscribing to a signal.
However, this means that a `SignalSubscriber` struct cannot have a
lifetime which exceeds the `SignalData` which contains it. In order to
fix the race in #978, one thread needs to be able to unsubscribe from a
signal (destroying the `SignalData` struct) while zero or more other
threads are in the process of calling the callbacks from a previous
emission of that signal (using the callback and `user_data` from zero or
more `SignalSubscriber` structs). Multiple threads could be calling
callbacks because callbacks are invoked in the `GMainContext` which
originally made a subscription, and GDBus supports subscribing to a
signal from multiple threads. In that case, the callbacks are dispatched
to multiple threads.
In order to allow the `SignalSubscriber` structs to outlive the
`SignalData` which contained their old match rule, store them in a
`GPtrArray` in the `SignalData` struct, and refcount them individually.
This commit in itself should make no functional changes to how GDBus
works, but will allow following commits to do so.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #978
This adds support for specifying multiple directories in the
GSETTINGS_SCHEMA_DIR environment variable by separating the values
using G_SEARCHPATH_SEPARATOR_S (colon on UNIX-like systems).
While programs could already register multiple custom GSettings schema
directories, it was not possible to achieve the same without writing
custom code, e.g. when using the gsettings command line tool.
Fixes#1998.
1) When parsing the executable name out of the command line,
see if the executable is rundll32.exe. If that is the case,
use the DLL name from its first argument as the "executable"
(this is used only for matching, and Windows Registry matches
these programs by their DLLs, so this is correct; for running
the application GLib would still use the command line, with
rundll32).
2) If an app runs with rundll32, ensure that rundll32 arguments
can be safely quoted. Otherwise GLib will break them with its
protective quotation.
Currently the code generated by gdbus-codegen uses
G_DBUS_CALL_FLAGS_NONE in its D-Bus calls, which occur for each method
defined by the input XML, and for proxy_set_property functions. This
means that if the daemon which implements the methods checks for
G_DBUS_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION and only does interactive
authorization if that flag is present, users of the generated code have
no way to cause the daemon to use interactive authorization (e.g. polkit
dialogs).
If we simply changed the generated code to always use
G_DBUS_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION, its users would have no
way to disallow interactive authorization (except for manually calling
the D-Bus method themselves).
So instead, this commit adds a GDBusCallFlags argument to method call
functions. Since this is an API break which will require changes in
projects using gdbus-codegen code, the change is conditional on the
command line argument --glib-min-version having the value 2.64 or
higher.
The impetus for this change is that I'm changing accountsservice to
properly respect G_DBUS_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION, and
libaccountsservice uses generated code for D-Bus method calls. So
these changes will allow libaccountsservice to continue allowing
interactive authorization, and avoid breaking any users of it which
expect that. See
https://gitlab.freedesktop.org/accountsservice/accountsservice/merge_requests/46
It might make sense to also let GDBusCallFlags be specified for property
set operations, but that is not needed in the case of accountsservice,
and would require significant work and breaking API in multiple places.
Similarly, the generated code currently hard codes -1 as the timeout
value when calling g_dbus_proxy_call*(). Add a timeout_msec argument so
the user of the generated code can specify the timeout as well.
Also, test this new API. In gio/tests/codegen.py we test that the new
arguments are generated if and only of --glib-min-version is used with a
value greater than or equal to 2.64, and in gio/tests/meson.build we
test that the generated code with the new API can be linked against.
The test_unix_fd_list() test also needed modification to continue
working now that we're using gdbus-test-codegen.c with code generated
with --glib-min-version=2.64 in one test.
Finally, update the docs for gdbus-codegen to explain the effect of
using --glib-min-version 2.64, both from this commit and from
"gdbus-codegen: Emit GUnixFDLists if an arg has type `h` w/
min-version".
Notification id (notify_id) is generated by notification daemon and
is valid only while daemon is running. If notification backend will
resend/reuse existing notification id (replace_id) after notification
daemon has been restarted it could replace wrong notification as same
id now can be used by different notification.
Previously, the documentation indicated that it was possible to call
g_tls_connection_handshake() after an initial handshake to trigger a
rehandshake, but only if TLS 1.2 or older is in use. However, there is
no documented way to ensure TLS 1.2 gets used. Nowadays, TLS 1.3 is used
by default.
I'm removing support for rehandshaking from glib-networking, as part of
a large refactoring where keeping rehandshakes would have entailed
significant additional complexity. So let's update the documentation to
indicate this is no longer ever supported. Applications should not
notice any difference.
Also, sync some previous handshake and rehandshake changes from
GTlsConnection to GDtlsConnection that were missed by mistake. I
try to remember to always update GDtlsConnection when touching
GTlsConnection documentation, but it's easy to forget.
We used XML to markup when we should have used our own brand of markdown
instead. This fixes the example being unreadable unless we trimmed the
XML away from it.
For the check "if (error != NULL)" to work as expected, the
create_server() (and create_server_full()) functions need to make
sure to return an error for all the possible failures, but this
might not always be the case.
Catch all the failures by testing for a non-NULL return value if there
was no error.
This shouldn't make any difference, because this code should only ever
be running in the main context that was thread-default at the time the
task was created, so it should already match the task's context. But
let's make sure, just in case.
They didn’t match the prototype generated by `gdbus-codegen`, which
meant that the FD list was being iterated incorrectly. Secondly, the
document ID list returned by the method was not NULL terminated, which
could lead to reading off the end of the list.
Somehow, neither of these bugs caused problems on Linux, but they did
cause problems on FreeBSD.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1983
Sadly, I forgot to update the documentation of
g_dtls_connection_handshake() last time I touched
g_tls_connection_handshake().
Let's also drop mention of STARTTLS, since that would use normal TLS,
not DTLS.
Reduce the number of iterations of things sent over a mock session bus
from different threads, to avoid the test spending quite so long
contested over the `gsignal.c` lock.
The test now takes about 10 seconds, according to `time`, rather than
around 100 or longer.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
By removing the cached global proxy in gdocumentportal.c, we can
re-enable the checks for proper shutdown of the session bus connection
in the dbus-appinfo.c test.
We can't use session_bus_down() in the test since gdocumentportal.c
holds a reference to the session bus connection, preventing it from
being finalised.
There are some GVfs locations (i.e. google-drive://, recent://), where
G_FILE_ATTRIBUTE_STANDARD_NAME is something tottaly different than
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME. Thus it would be nice to have
an easy way to show the display names. The only way currently to show
the display names is to use --attributes option, which is a bit
cumbersome. Let's add new --show-display-names option.
https://gitlab.gnome.org/GNOME/gvfs/issues/402
Those tests require Python, gobject-introspection and python-dbusmock
making them unsuitable to be run within the uninstalled test suite.
There are no restrictions of dependencies when it comes to installed
tests so use those to exercise GMemoryMonitor.
With debug enabled, g_dbus_connection_call_done() will throw a
g_warning() if the call failed (on purpose or not) while trying to the
serial of a non-existant reply.
(/builds/GNOME/glib/_build/gio/tests/gdbus-connection:26921): GLib-GIO-CRITICAL **: 10:10:16.311: g_dbus_message_get_reply_serial: assertion 'G_IS_DBUS_MESSAGE (message)' failed
This is a reimplementation of commit
4aba03562b from Will Thompson, but
conditional on the caller passing `--glib-min-version 2.64` to
`gdbus-codegen` to explicitly opt-in to the new behaviour.
From the commit message for that commit:
Previously, if a method was not annotated with org.gtk.GDBus.C.UnixFD
then the generated code would never contain GUnixFDList parameters, even
if the method has 'h' (file descriptor) parameters. However, in this
case, the generated code is essentially useless: the method cannot be
called or handled except in degenerate cases where the file descriptors
are missing or ignored.
Check the argument types for 'h', and if present, generate code as if
org.gtk.GDBus.C.UnixFD annotation were specified.
Includes a unit test too.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1726
This can be used by callers to opt-in to backwards-incompatible changes
to the behaviour or output of `gdbus-codegen` in future. This commit
doesn’t introduce any such changes, though.
Documentation and unit tests included.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1726
We got a complaint here that trashing via the
portal deletes the target of a symlink, not the
symlink itself. It turns out that following the
symlink already happens on the glib side.
https://github.com/flatpak/xdg-desktop-portal/issues/412
Skipped tests use "77" as the return value, so return 77 instead of 0
when the static-link.py test gets skipped because of a missing
environment variable.
If the fuse module is loaded but /dev/fuse doesn't exist, it's likely
that we're running in a rootless container, or a badly setup one, and we
won't be able to use fuse, so skip this test.
This happened on my local system using podman running as a normal user,
but this apparently works as expected in our CI[1].
[1]: https://gitlab.gnome.org/GNOME/glib/merge_requests/466
gtk-doc switched from DocBook to Markdown ages ago. There is no Markdown
equivalent for `<warning>`, so just drop it. It wasn’t adding anything
particularly valuable to the documentation.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1130
gtk-doc long since switched to Markdown, so we shouldn’t be emitting
DocBook `<link>` tags.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1130
Add a Python-based test wrapper for the `gdbus-codegen` executable,
similar to the existing tests for `glib-mkenums` and friends.
Add a few basic tests to begin with, but this doesn’t approach anywhere
near full coverage.
The next step is to move the existing Meson-based `gdbus-codegen` tests
from `gio/tests/meson.build` into the Python test suite.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1612
Previously, running `gdbus-codegen` with no arguments would exit
successfully with no output. While technically correct, that seems
unhelpful.
Require at least one interface file to be specified, so the user gets an
error message if they don’t specify any.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
It’s not particularly useful to put the gdbus-codegen version or the
name of the input file into the output from `gdbus-codegen`, and it
makes the output less reproducible. Drop it.
Also clarify the licensing.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1612
If not doing this it might happen that the cancelled signal is emitted
between reaching a reference count of 0 and finalizing the GSource, at
which point part of the GSource is already freed and calling any GSource
functions is dangerous.
Instead do this from the dispose function. At this time the GSource is
not partially freed yet and calling any GSource API is safe as long as
we ensure that we have a strong reference to the GSource before calling
any GSource API.
_kqsub_free assumes the caller has called _kqsub_cancel before calling
it. It checks if both 'deps' and 'fd' have been freed and aborts when
the condition is not met. Since the only caller of _kqsub_free is
g_kqueue_file_monitor_finalize, which does call _kqsub_cancel before
calling _kqsub_free, it seems to be correct for _kqsub_free to assert
values of these two members there.
However, it is possible for _kqsub_cancel to return early without
freeing any resource _kqsub_free expects to be freed. When the kevent
call fails, _kqsub_cancel does not free anything and _kqsub_free aborts
with assertion failure. This is an unexpected behavior, and it can be
fixed by always freeing resources in _kqsub_cancel.
Fixes: https://gitlab.gnome.org/GNOME/glib/issues/1935
"gio mount" doesn't print anything in case of success, however "gio mount -d"
prints "Mounted [id] at [mount_path]", which is inconsistent. It might probably
make sense for fstab volumes, but "gio mount -d" now support UUIDs which are
heavily used for daemon mounts and I think that it is not wise to print
"/run/user/$UID/gvfs" mount paths. The mount path can be still found over
"gio mount -l". Let's remove this message to make it more consistent.
"gio mount" only allows mounting volumes using device files, but not using
UUIDs. Volume monitors for various GVfs locations usually supports just UUIDs.
It would be handy to support them also for testing purposes (because
"g_file_mount_enclosing_volume()" does something else than "g_volume_mount()"
in case of shares provided by GOA volume monitor for example). Let's update
"-d" option to support also UUIDs.
https://gitlab.gnome.org/GNOME/gvfs/issues/251
It’s possible that one VFS operation will happen from a worker thread at
the same time as another is happening from the main thread, in which
case the static buffer which getpwnam() uses will be overwritten.
There’s a chance this will corrupt the results that one of the threads
receives.
Fix that by using the thread-safe getpwnam_r() version, via the new
g_unix_get_passwd_entry() function.
Fix the indentation of the surrounding block while we’re there.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1687
Those tests seem to regularly fail because a timeout (which we're
measuring outside the function that times out) is too long, which can
happen when the system is busy.
Don't run those tests unless "thorough" tests are requested. This
disables those tests by default.
Bail out! GLib-GIO:ERROR:../gio/tests/socket.c:1167:test_timed_wait: assertion failed (poll_duration < 112000): (114254 < 112000)
Bail out! GLib-GIO:ERROR:../gio/tests/cancellable.c:167:on_mock_operation_ready: assertion failed (error == (g-io-error-quark, 19)): error is NULL
Now we're returning the file type again, we need to mask it out to
compare with the mode. We can also check that the statbuf said the file
is a regular file.
Related: #1934
This reverts commit bfdc5fc4fc.
This changes the semantics of G_FILE_ATTRIBUTE_ID_UNIX_MODE, and we've
already found one user of the previous semantics (ostree).
Closes#1934
This function has numerous undocumented limitations. In particular, it
is not possible to ensure this function actually does anything. Document
these problems.
For many years after SSL 3.0 support was removed, we used this function
to indicate that we should perform protocol version fallback to the
lowest-supported protocol version, to workaround protocol version
intolerance. Nowadays this is no longer needed, and support has been
removed from glib-networking, so update the documentation.
GTlsConnection:rehandshake-mode has been deprecated since 2.60 using
the G_PARAM_DEPRECATED flag, but I forgot to add the right annotation to
the documentation. Oops.
The associated getter/setter functions were both deprecated properly.
This is the analogue of commit 7c4e6e9fbe, but applied to the
`GDBusMessage` parser, which does its own top-level parsing of the
variant format in D-Bus messages.
Previously, this code allowed arbitrary recursion of variant containers,
which could lead to a stack overflow. Now, that recursion is limited to
64 levels, as per the D-Bus specification:
https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling-signature
This includes a new unit test.
oss-fuzz#14870
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Tools like this should be configurable in a cross or native file. In
particular, if we are cross-compiling (with an executable wrapper like
qemu-arm), the build system ld is not necessarily able to manipulate
host system objects.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Otherwise we'll never test the EXTERNAL-only mode, because that relies
on testing the private macros
G_CREDENTIALS_UNIX_CREDENTIALS_MESSAGE_SUPPORTED and
G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED.
Fixes: 9f962ebe "Add a test for GDBusServer authentication"
Signed-off-by: Simon McVittie <smcv@collabora.com>
This bypasses any issues we might have with containers where IPv6 is
returned by name resolution (particularly since GNOME/glib!616) but
doesn't necessarily actually work.
This comes at a minor test-coverage cost: we don't test GDBusServer's
default behaviour when told to listen on "tcp:" or "nonce-tcp:", and
on systems where IPv6 is available, we don't test it. If we want to
do those, we should perhaps do them in separate tests, and disable
those tests when binding to ::1 doesn't work.
Mitigates: GNOME/glib#1912
Signed-off-by: Simon McVittie <smcv@collabora.com>
Whitelist a safe set of characters for use in header guards instead of
maintaining a (growing) blacklist.
The whitelist is intentionally short since reading up on all
peculiarities of the C and C++ standard for identifiers is not my idea
of fun. :)
Fixes#1379
g_assert() is compiled out by `G_DISABLE_ASSERT` and doesn’t give such
useful messages on failure.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
No need to clear it to NULL before every time it’s used, since we assert
that it’s never set.
This introduces no functional changes.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
This avoids failure to listen on the given address on non-Linux Unix
kernels, where abstract sockets do not exist and so unix:tmpdir is
equivalent to unix:dir.
To avoid bugs like this one recurring, run most of these tests using
the unix:dir address type, where Linux is equivalent to other Unix
kernels; just do one unix:tmpdir test, to check that we still
interoperate with libdbus when using abstract sockets on Linux.
Resolves: GNOME/glib#1920
Fixes: 9f962ebe "Add a test for GDBusServer authentication"
Signed-off-by: Simon McVittie <smcv@collabora.com>
Previously, we used unix:tmpdir, except in tests that verify that a
particular address type works (notably unix:dir). Now we use unix:dir
most of the time, and unix:tmpdir gets its own test instead.
This helps to ensure that the tests continue to work on non-Linux Unix
kernels, where abstract sockets do not exist and so unix:tmpdir is
equivalent to unix:dir, even in the common case where the developer has
only tried the test on Linux.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Otherwise, since GNOME/glib!1193, the listening socket won't be deleted,
and if we are not using abstract sockets (for example on *BSD), g_rmdir
will fail with ENOTEMPTY.
Fixes: 8e32b8e8 "gdbusserver: Delete socket and nonce file when stopping server"
Resolves: GNOME/glib#1921
Signed-off-by: Simon McVittie <smcv@collabora.com>
The `on_run()` function could be executed in any worker thread from the
`GThreadedSocketListener`, but didn’t previously hold a strong reference
to the `GDBusServer`, which meant the server could be finalised in
another thread while `on_run()` was still running.
This was not ideal.
Hold a strong reference to the `GDBusServer` while the socket listener
is listening, i.e. between every paired call to `g_dbus_server_start()`
and `g_dbus_server_stop()`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1318
Rather than when finalising it. They should be automatically recreated
if the server is re-started.
This is important for ensuring that all externally visible behaviour of
the `GDBusServer` is synchronised with calls to
g_dbus_server_{start,stop}(). Finalisation of the server object could
happen an arbitrarily long time after g_dbus_server_stop() is called.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1318
So that the tests all end up using separate `.dbus-keyring` directories,
and hence not racing to create and acquire lock files, use
`G_TEST_OPTION_ISOLATE_DIRS` to ensure they all run in separate
disposable directories.
This has the added benefit of meaning they don’t touch the developer’s
actual `$HOME` directory.
This reduces the false-failure rate of `gdbus-peer` by a factor of 9 for
me on my local machine.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1912
There’s actually no need for them to be global or reused between unit
tests, so move them inside the test functions.
This is one step towards eliminating shared state between the unit
tests.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1912
If the directory is overridden, for example when running tests, the
parent directory of `.dbus-keyrings` (i.e. the fake `$HOME` directory)
might not exist. Create it automatically.
This should realistically not have an effect on non-test code.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1912
These can be hit in the tests (if multiple tests run in parallel are
racing for `~/.dbus-keyrings/org_gtk_gdbus_general.lock` for a prolonged
period) and will cause spurious test failures due to the use of
`G_DEBUG=fatal-warnings`.
Instead, allow the error messages to be inspected programmatically.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1912
In particular, if libbdus is available, we test interoperability with
a libdbus client: see GNOME/glib#1831. Because that issue describes a
race condition, we do each test repeatedly to try to hit the failing
case.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Conceptually, a D-Bus server is really trying to determine the credentials
of (the process that initiated) a connection, not the credentials that
the process had when it sent a particular message. Ideally, it does
this with a getsockopt()-style API that queries the credentials of the
connection's initiator without requiring any particular cooperation from
that process, avoiding a class of possible failures.
The leading '\0' in the D-Bus protocol is primarily a workaround
for platforms where the message-based credentials-passing API is
strictly better than the getsockopt()-style API (for example, on
FreeBSD, SCM_CREDS includes a process ID but getpeereid() does not),
or where the getsockopt()-style API does not exist at all. As a result
libdbus, the reference implementation of D-Bus, does not implement
Linux SCM_CREDENTIALS at all - it has no reason to do so, because the
SO_PEERCRED socket option is equally informative.
This change makes GDBusServer on Linux more closely match the behaviour
of libdbus.
In particular, GNOME/glib#1831 indicates that when a libdbus client
connects to a GDBus server, recvmsg() sometimes yields a SCM_CREDENTIALS
message with cmsg_data={pid=0, uid=65534, gid=65534}. I think this is
most likely a race condition in the early steps to connect:
client server
connect
accept
send '\0' <- race -> set SO_PASSCRED = 1
receive '\0'
If the server wins the race:
client server
connect
accept
set SO_PASSCRED = 1
send '\0'
receive '\0'
then everything is fine. However, if the client wins the race:
client server
connect
accept
send '\0'
set SO_PASSCRED = 1
receive '\0'
then the kernel does not record credentials for the message containing
'\0' (because SO_PASSCRED was 0 at the time). However, by the time the
server receives the message, the kernel knows that credentials are
desired. I would have expected the kernel to omit the credentials header
in this case, but it seems that instead, it synthesizes a credentials
structure with a dummy process ID 0, a dummy uid derived from
/proc/sys/kernel/overflowuid and a dummy gid derived from
/proc/sys/kernel/overflowgid.
In an unconfigured GDBusServer, hitting this race condition results in
falling back to DBUS_COOKIE_SHA1 authentication, which in practice usually
succeeds in authenticating the peer's uid. However, we encourage AF_UNIX
servers on Unix platforms to allow only EXTERNAL authentication as a
security-hardening measure, because DBUS_COOKIE_SHA1 relies on a series
of assumptions including a cryptographically strong PRNG and a shared
home directory with no write access by others, which are not necessarily
true for all operating systems and users. EXTERNAL authentication will
fail if the server cannot determine the client's credentials.
In particular, this caused a regression when CVE-2019-14822 was fixed
in ibus, which appears to be resolved by this commit. Qt clients
(which use libdbus) intermittently fail to connect to an ibus server
(which uses GDBusServer), because ibus no longer allows DBUS_COOKIE_SHA1
authentication or non-matching uids.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Closes: https://gitlab.gnome.org/GNOME/glib/issues/1831
On Linux, if getsockopt SO_PEERCRED is used on a TCP socket, one
might expect it to fail with an appropriate error like ENOTSUP or
EPROTONOSUPPORT. However, it appears that in fact it succeeds, but
yields a credentials structure with pid 0, uid -1 and gid -1. These
are not real process, user and group IDs that can be allocated to a
real process (pid 0 needs to be reserved to give kill(0) its documented
special semantics, and similarly uid and gid -1 need to be reserved for
setresuid() and setresgid()) so it is not meaningful to signal them to
high-level API users.
An API user with Linux-specific knowledge can still inspect these fields
via g_credentials_get_native() if desired.
Similarly, if SO_PASSCRED is used to receive a SCM_CREDENTIALS message
on a receiving Unix socket, but the sending socket had not enabled
SO_PASSCRED at the time that the message was sent, it is possible
for it to succeed but yield a credentials structure with pid 0, uid
/proc/sys/kernel/overflowuid and gid /proc/sys/kernel/overflowgid. Even
if we were to read those pseudo-files, we cannot distinguish between
the overflow IDs and a real process that legitimately has the same IDs
(typically they are set to 'nobody' and 'nogroup', which can be used
by a real process), so we detect this situation by noticing that
pid == 0, and to save syscalls we do not read the overflow IDs from
/proc at all.
This results in a small API change: g_credentials_is_same_user() now
returns FALSE if we compare two credentials structures that are both
invalid. This seems like reasonable, conservative behaviour: if we cannot
prove that they are the same user, we should assume they are not.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Otherwise we’ll end up using the host’s `objcopy`, which will output
object files in the wrong format.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1916
This reverts commit 4aba03562b, preserving
the new tests but adjusting them to assert that the old behaviour is
restored.
As expected, there were a few projects which broke because of this.
Unfortunately, in one case the breakage crosses a project boundary:
sysprof ships D-Bus introspection XML, which is consumed by mutter and
passed through gdbus-codegen.
Since sysprof cannot add this annotation without breaking its existing
users, a warning is also not appropriate.
https://gitlab.gnome.org/GNOME/jhbuild/issues/41https://gitlab.gnome.org/GNOME/sysprof/issues/17https://gitlab.gnome.org/GNOME/glib/issues/1726
Previously we were keeping a pointer to the `GFileMonitor` in a
`GFileMonitorSource` instance, but since we weren’t keeping a strong
reference, that `GFileMonitor` instance could be finalised from another
thread at any point while the source was referring to it. Not good.
Use a weak reference, and upgrade it to a strong reference whenever the
`GFileMonitorSource` is referring to the file monitor.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1903
It’s not enough to unref the monitor, since the GLib worker thread might
still hold a reference to it.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1903
`DesktopFileDir` pointers are passed around between threads: they are
initially created on the main thread, but a pointer to them is passed to
the GLib worker thread in the file monitor callback
(`desktop_file_dir_changed()`).
Accordingly, the `DesktopFileDir` objects either have to be
(1) immutable;
(2) reference counted; or
(3) synchronised between the two threads
to avoid one of them being used by one thread after being freed on
another. Option (1) changed with commit 99bc33b6 and is no longer an
option. Option (3) would mean blocking the main thread on the worker
thread, which would be hard to achieve and is against the point of
having a worker thread. So that leaves option (2), which is implemented
here.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1903
When the _g_dbus_worker_flush_sync() schedules the 'data' and releases
the worker->write_lock, it is possible for the GDBus worker thread thread
to finish the D-Bus call and acquire the worker->write_lock before
the _g_dbus_worker_flush_sync() re-acquires it in the if (data != NULL) body.
When that happens, the ostream_flush_cb() increases the worker->write_num_messages_flushed
and then releases the worker->write_lock. The write lock is reacquired by
the _g_dbus_worker_flush_sync(), which sees that the while condition is satisfied,
thus it doesn't enter the loop body and immediately clears the data members and
frees the data structure itself. The ostream_flush_cb() is still ongoing, possibly
inside flush_data_list_complete(), where it accesses the FlushData, which can be
in any stage of being freed.
Instead, add an explicit boolean flag indicating when the flush is truly finished.
Closes#1896
`-1` isn’t a valid member of the enum, so cast to `int` first. This
fixes a compiler warning on Android.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Mounts are currently completed only if the prefix looks like scheme,
however, this doesn't work well if the mounts have also path component.
Let's always include them to fix this issue. The mounts are cached by the
volume monitors, so it should not significantly affect the performance.
Currently, "gio mount google-drive<tab>" isn't completed even though
that volume exists for google-drive://oholy@redhat.com/. Let's use
"gio mount -li" output to complete also activation roots of volumes.
Currently, "gio list file:///h<tab>" doesn't complete "file:///home"
because the result of "dirname file:///h" is not "file:///" but "file:/",
which breaks the consequent logic. Let's subtract basename from the
path in order to workaround this issue.
Fixes build failure:
../gio/gunixmounts.c: In function ‘_g_get_unix_mounts’:
../gio/gunixmounts.c:742:53: error: ‘struct mnttab’ has no member named ‘mnt_opts’; did you mean ‘mnt_mntopts’?
742 | mntent.mnt_opts,
| ^~~~~~~~
| mnt_mntopts
Signed-off-by: Alan Coopersmith <alan.coopersmith@oracle.com>
g_date_time_add_seconds() and g_date_time_add_full() use floating-point
seconds, which can result in the value varying slightly from what's
actually on disk. This causes intermittent test failures in
gio/tests/g-file-info.c on Debian i386, where we set a file's mtime
to be 50µs later, then read it back and sometimes find that it is only
49µs later than the previous value.
I've only seen this happen on i386, which means it might be to do with
different floating-point rounding when a value is stored in the 80-bit
legacy floating point registers rather than in double precision.
g_date_time_add() takes a GTimeSpan, which is in microseconds;
conveniently, that's exactly what we get from the GFileInfo.
Bug-Debian: https://bugs.debian.org/941547
Signed-off-by: Simon McVittie <smcv@collabora.com>
If we're cross-compiling, the installed-tests are useful even if we
can't run them on the build machine: we can copy them to the host
machine (possibly via a distro package like Debian's libglib2.0-tests)
and run them there.
While I'm changing the build-tests condition anyway, deduplicate it.
Based on a patch by Helmut Grohne.
Bug-Debian: https://bugs.debian.org/941509
Signed-off-by: Simon McVittie <smcv@collabora.com>
Skip it on systems which don’t support it, rather than compiling it out.
That gives us more information from test runs about which tests are
being run on which architectures.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
As with the previous commit, `st_mode` contains both the file type
(regular file, directory, symlink, special, etc.) and the file mode. For
`G_FILE_ATTRIBUTE_ID_UNIX_MODE`, we only want the file mode — so mask
`st_mode` with `~S_IFMT`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
chmod() technically only accepts file modes, not the file type and mode
as returned by stat(). Filter by `S_IFMT` to avoid sending the file
type (regular file, directory, symbolic link, etc.).
In practice, chmod() ignores anything except the file mode, but we might
as well comply with the specification.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
`GFile` always checks whether these vfuncs are `NULL` before calling
them, so document that it’s safe for implementations of `GFile` to not
implement them.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
The caller assumes that an unimplemented vfunc means that copying is
unsupported (and falls back to its internal copy implementation), so
there’s no point in implementing the vfunc just to unconditionally
return `G_IO_ERROR_NOT_SUPPORTED`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Rather than defining a vfunc which only ever returns
`G_IO_ERROR_NOT_SUPPORTED`, just don’t define the vfunc at all. The
caller in `GFile` interprets this as symlinks not being supported — so
we get the same behaviour, but without spending a vfunc call on it.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
The string is already translated in `GLocalFile`, so this doesn’t
introduce a new translatable string.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
This sets the `G_FILE_COPY_DEFAULT_PERMS` flag on the operation,
creating the copied file with default permissions rather than the same
permissions as the source file.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #174
If a copy operation is started with `G_FILE_COPY_TARGET_DEFAULT_PERMS`,
don’t create the destination file as private. Instead, create it with
the process’ current umask (i.e. ‘default permissions’).
This is a partial re-work of commit d8f8f4d637, with
input from Ondrej Holy.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #174
The actual parameter name in g_file_attribute_matcher_new()
attributes, so change the param reference to match. This way,
doc tools can create a proper link.
g_file_info_set_modification_time() and
g_file_info_set_modification_date_time() set the
G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC attribute in addition to
G_FILE_ATTRIBUTE_TIME_MODIFIED, so microsecond precision is available
when provided by the caller, so mention both attributes in the docs.
Currently, there is no quick way to find whether and element is already
part of a list store, except for manually writing a for-loop and calling
`g_list_model_get_item()` and breaking when you find the item.
This is mostly just a small API addition to support this use case.
Fixes https://gitlab.gnome.org/GNOME/glib/issues/1011
When compiling GLib with `-Wsign-conversion`, we get various warnings
about the atomic calls. A lot of these were fixed by
3ad375a629, but some remain. Fix them by
adding appropriate casts at the call sites.
Note that `g_atomic_int_{and,or,xor}()` actually all operate on `guint`s
rather than `gint`s (which is what the rest of the `g_atomic_int_*()`
functions operate on). I can’t find any written reasoning for this, but
assume that it’s because signedness is irrelevant when you’re using an
integer as a bit field. It’s unfortunate that they’re named a
`g_atomic_int_*()` rather than `g_atomic_uint_*()` functions.
Tested by compiling GLib as:
```
CFLAGS=-Wsign-conversion jhbuild make -ac |& grep atomic
```
I’m not going to add `-Wsign-conversion` to the set of default warnings
for building GLib, because it mostly produces false positives throughout
the rest of GLib.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1565
They provide more detailed failure messages, and aren’t compiled out
when building with `G_DISABLE_ASSERT`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
When future porting deprecated code to use
g_file_info_get_modification_date_time() we risk a number of breakages
because the current implementation also requires the additional use of
G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC. This handles that situation gracefully
and returns a GDateTime with less precision.
Applications that want the additional precision, are already using the
additional attribute.
(Minor tweaks by Philip Withnall.)
This should make the code a bit easier to reason about, and squash some
static analysis warnings.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1767
The macros for the probes confuse the static analyser, and are often
called with arguments which the analyser things shouldn’t be used any
more (for example, the address of a block of memory which has just been
freed).
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1767
These squash various warnings from `scan-build`. None of them are
legitimate bugs, but some of them do improve code readability a bit.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1767
Previously, if a method was not annotated with org.gtk.GDBus.C.UnixFD
then the generated code would never contain GUnixFDList parameters, even
if the method has 'h' (file descriptor) parameters. However, in this
case, the generated code is essentially useless: the method cannot be
called or handled except in degenerate cases where the file descriptors
are missing or ignored.
Check the argument types for 'h', and if present, generate code as if
org.gtk.GDBus.C.UnixFD annotation were specified.
This change will break any existing code which refers to the (useless)
wrappers for such methods. The workaround for such code is to add the
org.gtk.GDBus.C.UnixFD annotation, which will cause the same generated
code to be emitted before and after this change.
If this is found to cause widespread problems, we can explore a
different approach (perhaps emitting a warning from the code generator,
or annotating the symbols as deprecated).
https://gitlab.gnome.org/GNOME/glib/issues/1726
Instead of letting each directory to find its way to link with libdl,
it is easier to put the check in the top level, so its result can be
used by all directories.
It is a follow-up of https://gitlab.gnome.org/GNOME/glib/merge_requests/810.
The header file was installed when building using autotools, but was
inadvertently omitted in the meson targets.
Luckily, ABI is not impacted, since gnativesocketaddress.c was always
compiled and linked into libgio.
Fixes: #1854
The gobject introspection comments have a reference to an incorrect
class: they have, as 'self', the GSubprocess class instead of
GSubprocessLauncher.
This patch fixes this.
g_settings_backend_watch() uses a weak notify for keeping track of
the target. There's an explanation why this is supposed to be safe but
that explanation is wrong.
The following could happen before:
1. We have the target stored in the watch list
2. The last reference to the target is dropped in thread A and we end up
in g_settings_backend_watch_weak_notify() right before the mutex
3. g_settings_backend_dispatch_signal() is called from another thread B
and gets the mutex before 2.
4. g_weak_ref_init() is called on the target from thread B, which at
this point has a reference count of exactly one (see g_object_unref()
where it calls the weak notifies)
5. Thread A continues at 3. and drops the last reference and destroys
the object. Now the GWeakRef from 4. points to a destroyed object. Note
that GWeakRefs would be cleared before the weak notifies are called
6. At some later point another thread g_weak_ref_get() is called by
g_settings_backend_invoke_closure() and accesses an already destroyed
object with refcount 0 from the GWeakRef created in 4. by thread B (or
worse, already freed memory that was reused).
Solve this by actually storing a GWeakRef of the target in the watch
list and only access the target behind it via the GWeakRef API, and then
pass a strong reference to the notification dispatch code.
The weak notify is only used to remove the (potentially with empty
GWeakRef) target from the list of watches and the only place that
compares the target by pointer instead of going through the GWeakRef
API.
Fixes https://gitlab.gnome.org/GNOME/glib/issues/1870
If we fail to create a GWinhttpFile for a URI (for example, because it’s
an invalid URI or is badly encoded), don’t just return NULL. Instead,
fall back to the wrapped VFS which might be able to handle it instead.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1819
It can return NULL if the URI was badly encoded or couldn’t be handled
by Windows’ API.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1819
It cannot return a NULL value, as none of its callers have error
handlng. Add an assertion to check the values returned by the VFS
implementations.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1819
This fixes use of `GIO_USE_VOLUME_MONITOR=help`, and simplifies the
code. The reason this wasn’t used already seems to just be because it
was missed when `_g_io_module_get_default_type()` was introduced in
2013. The previous `get_default_native_class()` code in
`gunionvolumemonitor.c` was introduced in 2007.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Closes: #1881
Deletes the skip annotation from g_cancellable_source_new(). This was
originally added because GSource wasn't introspectable, but this is no
longer an issue as G_TYPE_SOURCE was added in 2.30.
Fixes: #1877
When resetting a key in the delayed settings backend,
g_settings_backend_changed() was not called to notify the backend of
the change.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1309
This fix build error for projects that use gnome.compile_resources()
when glib is built as a subproject and not installed on the build
machine.
Note that this is not working for cross compilation cases, because it
would require to compile everything twice (for host and build machines).
A better solution would be to rewrite those tools in python. See #1859.
They use the deprecated GTimeVal type, which is not year 2038 safe, so
have to be deprecated.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1438
These are alternatives to g_file_info_{get,set}_modification_time(),
which will soon be deprecated due to using the deprecated GTimeVal
type, which is not year 2038 safe.
The new APIs take a GDateTime instead.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1438
The event source used to handle inactivity_timeout doesn't hold a
reference on the application. Therefore, it is possible for callback
function of the event source to run after the application has been
freed, leading to use-after-free problem. To avoid the problem, we
should remove the event source before the application is freed.
This should fix SIGBUS crash of gio/tests/gapplication on FreeBSD.
https://gitlab.gnome.org/GNOME/glib/issues/1846#note_566550
These are here to prevent linker errors, since `gcontenttype.[ch]`
aren’t compiled on Windows or macOS.
The implementations are stubs to be filled out by someone who knows each
platform, at some point in the future.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1791
We're using the `install` argument for configure_file() all over the
place.
The support for an `install` argument for configure_file() was added in
Meson 0.50, but we haven't bumped the minimum version of Meson we
require, yet; which means we're getting compatibility warnings when
using recent versions of Meson, and undefined behaviour when using older
versions.
The configure_file() object defaults to `install: false`, unless an
install directory is used. This means that all instances of an `install`
argument with an explicit `true` or `false` value can be removed,
whereas all instances of `install` with a value determined from a
configuration option must be turned into an explicit conditional.
The comment previously said ‘never %NULL’, but it wasn’t clear whether
this meant `(not nullable)` or `(not optional)`. From looking at the
code, it means `(not optional)`.
Clarify things by removing the prose. The annotations themselves should
be clear and explicit enough.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Closes: #1836
We want to use the keyfile backend in sandboxes,
but we want to avoid people losing their existing
settings that are stored in dconf. Flatpak does
a migration from dconf to keyfile, but only if
the app explictly requests it.
From an app perspective, there are two steps to
the dconf->keyfile migration:
1. Request that flatpak do the migration, by adding
the migrate-path key to the metadata
2. Stop adding the 'dconf hole' to the sandbox
To keep us from switching to the keyfile backend
prematurely, look at whether the app has stopped
requesting a 'dconf hole' in the sandbox.
The plugin modules in these tests get statically linked with a separate
copy of GLib so they end up calling vfuncs in their own copy of GLib.
Fixes#1648
v7, based on a patch by mrgard (GNOME/glib#1635)
make w32_adapter_ipv4_addr() C90-compliant
check for ERROR_BUFFER_OVERFLOW when calling GetAdaptersAddresses()
code-style fixes
indentation fixes
use g_try_(re)alloc and g_free
style suggestions by pwithnall
drop uni_count variable
cap maximum allowed interface name string length according to windows documentation
Fixes: #1635
We need to enable building the dirent and gnulib sources for clang-cl,
as we are still using the Microsoft-style headers and lib's and CRT.
We need to also do this for the following, for similar reasoning:
-Symbol export (via __declspec(dllexport))
-Dependency discovery without pkg-config files
-long long and ssize_t detection
We do, however, enable the autoptr tests for clang-cl builds. Note that
at this point real MSVC builds are still better supported than clang-cl
builds, and it will likely remain so for at least the near future,
alhtough real MSVC builds of the GTK stack are consumable and are usable
by clang-cl.
In _g_object_unref_and_wait_weak_notify() we take a weak reference and
then call g_object_unref() in an idle callback, which may look like
we're dropping a strong reference without having one. So change the
comment to make it more clear that the reference being dropped is held
by the caller.
Now that we're not calling g_object_run_dispose() indirectly in
g_test_dbus_down() (see commit "Revert "gtestdbus: Properly close server
connections""), the test gdbus-connection-loss is failing with the
message "Bail out! GLib-GIO-FATAL-WARNING: Weak notify timeout, object
ref_count=1". This is because we're holding a reference to the singleton
connection object while calling session_bus_down() in the test's main().
So then we end up waiting for 30 seconds in
_g_object_unref_and_wait_weak_notify() for the GWeakNotify to be
triggered, which never happens.
The fix is to unref the connection before calling session_bus_down().
This is consistent with how other tests work, and is safe because the
only method called on the connection has already errored out, as
asserted by the test.
This reverts commit c37cd19fee.
Now that we've reverted the commit "gtestdbus: Properly close server
connections", g_test_dbus_down() no longer returns early and we no
longer need this workaround. Since the gdbus-names test seems to
properly unref its GDBusConnection objects it's not clear to me why it
needed the sleep to succeed. However even at the time the failure wasn't
reproducible according to this comment[1] so it's probably not worth
spending more effort trying to reproduce it now.
[1] https://gitlab.gnome.org/GNOME/glib/issues/787#note_214235
This reverts commit baf92d09d6.
Closes#787
According to the original commit, this change was made because otherwise
g_test_dbus_down() following a g_test_dbus_stop() hangs until it times
out. The timeout being referred to is the 30 seconds which are waited by
_g_object_unref_and_wait_weak_notify() for the GWeakNotify to be
triggered when the last strong reference to the singleton
GDBusConnection object is dropped. But the patch was not correct and the
leak should have instead been fixed by having the last strong reference
holder drop their reference on the GDBusConnection before calling
g_test_dbus_down(). Timing out after 30 seconds is the desired behavior
in the case where someone holds a reference to the singleton for that
entire period.
There are a few problems with this patch. First, as pointed out here[1],
calling g_object_run_dispose() in the idle callback means we are causing
the GWeakNotify to trigger ~immediately rather than waiting 30 seconds
to give another owner a chance to unref. Second, since someone else may
still hold a reference on the object being disposed, they may call
methods on it after it's been disposed which can seg fault as documented
here[2] and as I also saw recently in another project.
It's unclear what the original leak being fixed was, but many have been
fixed between 2013 and now. I ran all the unit tests under valgrind, and
some do fail (some consistently and some intermittently) but none of the
failures seem to only happen after this reversion commit. I also
couldn't find anywhere in the valgrind output where any GDBusConnection
objects are definitely being lost.
[1] https://gitlab.gnome.org/GNOME/glib/issues/787#note_214226
[2] https://gitlab.gnome.org/GNOME/glib/issues/787#note_214237
For several years now (I haven’t looked up the exact date),
`gnome-terminal` has preferred being called as `gnome-terminal
--terminal-args -- /some/other/program --its-args` rather than as
`gnome-terminal --terminal-args -x /some/other/program --its-args`.
Since 2017 it has warned about uses of `-x` (see
ad4edbd118).
So we should change our calling convention for it.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
There seems to be no reason to do so, and since the `appinfo` test was
ported to use `G_TEST_OPTION_ISOLATE_DIRS`, it has been causing
coredumps to accumulate. `gnome-terminal` was chosen as the terminal,
but it couldn’t find its GSettings schemas due to all the XDG
environment variables being cleared to `/dev/null` by
`G_TEST_OPTION_ISOLATE_DIRS`.
In order to keep using `gnome-terminal` as a subprocess in the tests,
we’d need to explicitly set up its environment so it can load the right
GSettings schemas. That’s a lot of work for not much gain.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #436
This commit changes a comment in _g_dbus_worker_do_read_cb() to be
slightly more useful. At least in my experience debugging an
intermittent unit test failure in another project, this failure
condition occurred because although g_test_dbus_down() ensures that the
session GDBusConnection has exit-on-close set to FALSE before killing
its dbus-daemon, there was still a GDBusConnection on the system bus
which hit this failed read code path, because we had
DBUS_SYSTEM_BUS_ADDRESS set to the address of the #GTestDBus daemon, to
appease libudisks.
Also, make a few other minor improvements to the docs.
On Visual Studio, Meson builds modules as xxxx.dll, not libxxxx.dll when
xxxx is specified as the name for the shared_module() build directive.
This means that in the test programs if we expect for libxxxx for the
module name, the test will fail as there is no libxxxx.dll but there is
xxxx.dll. This makes the test program look for the module files
correctly.
This makes use of the string we now have from glib-private.h in the
last commit so that setlocale() sets the default system locale
correctly and therefore show the translated messages properly.
Fixes issue #1169.
Using the generic marshaller has drawbacks beyond performance. One such
drawback is that it breaks the stack unwinding from the Linux kernel due
to having unsufficient data to walk past ffi_call_unixt64. That means that
performance profiling by application developers looks grouped among
seemingly unrelated code paths.
While we can't fix the kernel unwinding here, we can provide proper
c_marshallers and va_marshallers for objects within Gio so that
performance profiling of applications is more reliable.
Related to GNOME/Initiatives#10
If c_marshaller is provided during g_signal_new() registration, the
automatic va_marshaller will not be set. If we leave the c_marshaller as
NULL in the simple cases, both a c_marshaller and va_marshaller will be
set for us.
This is particularly helpful when dealing with stack traces from Linux
perf, which often cannot unwind the stack beyond the ffi_call_unix64
stack-frame on x86_64.
Related to GNOME/Initiatives#10
This ensures that D-Bus connections established with unix:dir and
unix:path addresses actually work properly. Previously, we only tested
unix:tmpdir and TCP addresses.
This is not going to have much any effect currently since stop() just
disconnects a signal handler (that is going to be disconnected in
finalize anyway) and stops the socket service (that is going to be
destroyed in finalize), but it makes sense to do here for robustness.
unix:dir= addresses are exactly the same as unix:tmpdir= addresses,
already supported by GDBus, except they forbid use of abstract sockets.
This is convenient for situations where abstract sockets are
impermissible, such as when a D-Bus client inside a network namespace
needs to connect to a server running in a different network namespace.
An abstract socket cannot be shared between two processes in different
network namespaces.
Applications could use unix:path= addresses instead, so this is only a
convenience, but there's no good reason not to support unix:dir=.
Currently it is not supported simply because unix:dir= is a relatively
recent addition to the D-Bus spec.
It's somewhat unrealistic to use a GDBusServer without a
GDBusAuthObserver, because most D-Bus servers want to be like the
standard session bus (the owning user can connect) rather than being
like the standard system bus (all users can connect, the server is a
security boundary, and many bugs are security vulnerabilities).
Signed-off-by: Simon McVittie <smcv@collabora.com>
This is simpler and more robust than DBUS_COOKIE_SHA1, which relies
on assumptions about random numbers and a secure home directory.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Authentication is about proving who I am; authorization is about
whether, given the knowledge of who I am, I am allowed to do something.
GDBusServer and GDBusConnection carry out authentication automatically,
but rely on the library user to carry out authorization.
Signed-off-by: Simon McVittie <smcv@collabora.com>
This is useful information for implementors of portable software to know
whether they can rely on credentials-passing.
Signed-off-by: Simon McVittie <smcv@collabora.com>
Previously, its tests were being run in the build directory, which is
fine (it should always be writable). If multiple tests were run in
parallel, for example with Meson’s `--repeat` option, their test files
would collide.
Fix that by running each test instance in a separate subdirectory of
`/tmp`.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1634
It is expected that `g_file_move()` moves symlink file itself, not its
target. Unfortunately, copy and delete fallback passes `GFileCopyFlags`
and don't explicitly use `G_FILE_COPY_NOFOLLOW_SYMLINKS`. This may cause
that symlink target is copied and symlink itself is removed. Let's
explicitly pass `G_FILE_COPY_NOFOLLOW_SYMLINKS` to the copy operation to
prevent this unexpected behavior.
https://gitlab.gnome.org/GNOME/glib/issues/986
The `G_FILE_COPY_NOFOLLOW_SYMLINKS` flag doesn't make sense for move operation,
neither local implementation doesn't handle this flag in any way. Therefore
this paragraph should be removed from the docs (it was probably copy&pasted
from `g_file_copy()` docs by mistake).
Closes: https://gitlab.gnome.org/GNOME/glib/issues/986
Add a case for when the IPv6 result comes back negative and the IPv4
result is significantly delayed. This is exactly the case that causes
the bug addressed by GNOME/glib!865
The "happy eyeballs" RFC states that on receiving a negative response
for an IPv6 address lookup, we should wait for the IPv4 lookup to
complete and use any results we get from there.
The current code was not doing that: it was rather setting a timeout for
failing the resolution entirely. In scenarios where the IPv4 response
comes more than 50ms after the IPv6 response (which is easily attainable
under valgrind in certain configurations) this means that the IPv4
response will never come.
Remove the timeout and just wait.
See merge request GNOME/glib!865
It should produce a generic result, but not crash. It was previously
crashing on macOS.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1729
g_assert_*() give more helpful error messages on failure, and aren’t
compiled out by G_DISABLE_ASSERT.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
This was introduced in commit 7846d6154a: g_subprocess_get_identifier()
will return NULL after the subprocess has exited, and the subprocess in
the `noop` test will exit as soon as it has started spawning. So if the
scheduler scheduled the testprog subprocess quickly, descheduled the
parent test process until the testprog exited, then the return value
from g_subprocess_get_identifier() would be NULL.
Move the g_subprocess_get_identifier() test to one which calls testprog
in `sleep-forever` mode, since that is guaranteed not to exit until
killed (which we do later in the test).
Signed-off-by: Philip Withnall <withnall@endlessm.com>
The most useful ones were already listed in the pkg-config file, but
some others (notably, `gio-querymodules`) were not. List them in the
pkg-config file with their installed paths so that the right binary is
used if GIO is installed in a non-default path.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1796
`NM_STATE_CONNECTED_SITE` is documented to mean that a default route is
available, but that the internet connectivity check failed. A default
route being available is compatible with the documentation for
GNetworkMonitor:network-available, which should be true if the system
has a default route for at least one of IPv4 and IPv6.
https://developer.gnome.org/NetworkManager/stable/nm-dbus-types.html
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1788
More vectors will give an error and we can simply clamp here and
consider it like a short write instead.
In case of GSocketOutputStream this is done here instead of inside
GSocket before calling sendmsg() because we we can't generically handle
short writes when sending messages on a socket, e.g. for datagram
sockets this causes only part of the datagram to be sent and an error
would be more useful in this case than sending corrupted data.
Also reduce the fallback limit to 16 in gsocket.c as that's the minimum
value required by POSIX and add a static assertion that the limit is
never bigger than G_MAXINT as that's the type recvmmsg/sendmmsg take.
These have all been documented as deprecated for a long time, but we’ve
never had a way to programmatically mark them as deprecated. Do that
now.
This is based on the list of deprecations from the reverted commit
80fcb1bc2.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #638
This code uses, or tests, deprecated functions, types or macros; so
needs to be compiled with deprecation warnings disabled.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
When defining deprecated macros, annotate them with
`GLIB_DEPRECATED_MACRO_IN_*()` and `GLIB_DEPRECATED_MACRO_IN_*_FOR()` to
conditionally emit warnings if people use them, depending on their
declared minimum and maximum GLib version requirements (see
`GLIB_VERSION_MIN_REQUIRED` and `GLIB_VERSION_MAX_ALLOWED`).
The old way of doing this was for users to define `G_DISABLE_DEPRECATED`
if they didn’t want to use deprecated APIs, but it reported errors via
missing symbols, and wasn’t version-dependent. It’s being phased out.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
file_copy_fallback creates new files with default permissions and
set the correct permissions after the operation is finished. This
might cause that the files can be accessible by more users during
the operation than expected. Use G_FILE_CREATE_PRIVATE for the new
files to limit access to those files.
When an application is launched using Launch Services
osx will add an extra parameter which we were not
handling and then gapplication would abort. Instead we make
an initial parsing and like this we avoid the abort if this
parameter is provided
Fixes https://gitlab.gnome.org/GNOME/glib/issues/1784
The caller cannot assume that the lists returned by various GSettings
functions (for example, lists of keys or schemas) will be returned in
any particular order.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1781
The parent GNetworkAddress contains a shared list of resolved
addresses that is used as a cache for multiple enumerations.
This commit ensures that the cache is only set upon completion of
DNS lookups and only read once by enumerations to avoid being in a
bad state.
Fixes#1771
We miss releasing the async operation's reference on a state object in
one of the error cases.
The call to connection_attempt_remove() (although it calls unref
internally) is not sufficient because this is releasing the reference
that the list owns.
Closes#1774
Spotted in https://gitlab.gnome.org/GNOME/mutter/issues/586. Bad input
on GAppLaunchContext environment manipulation functions is caught by
inner code, but the warning is not seemingly related.
Add precondition checks to these functions so it's clear where does the
bad input come from.
The network-available property can be asserted by querying the NMState
describing the current overval network state, instead of the
NMConnectivityState. The advantage of the NMState is that is reflects
immediately the network state modification, while the connectivity
state is tested at a fixed frequency.
Add support for mate-terminal and xfce4-terminal with higher precedence
over xterm as it's likely people that have those want to use them.
They both use the gnome-terminal `-x` switch instead of xterm's `-e`.
Some of these have a negative master/slave connotation, and they add no
value. Change or drop them.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Since out-of-source-tree builds are now used after switching to meson,
we don't need .gitignore files in the source directories to ignore
build artifacts.
This fixes build errors when doing a meson build after an autotools
build, because generated files such as gio/xdp-dbus.c won't show up in
a `git status`, or be removed by a `git clean -f`, and so it won't be
obvious that such files need to be removed for the meson build to
succeed.
The `monitor` test was originally written to test GFileMonitor with
directories. Over time, `testfilemonitor` acquired units for testing
directories as well, which made the `monitor` test reduntant.
We are manually tracking the completion state of the connect task
so avoid just calling g_task_return_error_if_cancelled() without
checking that.
Fixes#1747
Currently, there is no way to prevent tests from building using meson.
When cross-compiling, building the tests isn't necessary.
Instead, only build the tests on the following conditions:
1) If not cross-compiling.
2) If cross-compiling, and there is an exe wrapper.
Other GCC-like implementations of ld/objcopy (like LLVM) don’t yet
support the right command line arguments, so can’t compile the test.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
https://gitlab.gnome.org/GNOME/glib/issues/1709
This introduces no functional changes, but combines two duplicated lists
and makes the meson.build file a little easier to follow.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1711
After repeated local testing, I can’t reproduce failures with them:
meson test --repeat 5000 gdbus-auth
meson test --repeat 5000 gdbus-bz627724
meson test --repeat 5000 gdbus-connection
The FreeBSD failures from pthread calls mentioned in #1614 should
probably manifest as use-after-free for GMutex or pthread_mutex_t on
Linux. Failing that, I haven’t seen any relevant FreeBSD failures on CI
for at least a month, so if it’s not fixed, the chances of debugging are
very low.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
https://gitlab.gnome.org/GNOME/glib/issues/1614
Add g_steal_pointer() and g_clear_object() calls in various places to
clarify the ownership transfers for GDBusMessage instances, in a bid to
understand what’s going on in this code and to try to find a
use-after-finalize problem.
This introduces no functional changes, but hopefully makes the code a
little clearer.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
If the filter function for an outgoing message fails to copy the
GDBusMessage, that failure was previously ignored, and GDBusMessage
methods could be called on a NULL instance.
Avoid that.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Rather than keeping a reference to the GThreadedSocketService as the
user_data for every thread pool job, add it to a member of the per-job
data struct (GThreadedSocketServiceData). This should make no
difference overall, as it’s just moving the refcounting around, but it
does seem to fix an occasional double-unref crash on shutdown where the
GThreadedSocketService is unreffed during finalisation.
In any case, it makes the object ownership clearer.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Check for RTLD_NEXT being present, and disable the gsocketclient-slow
test if it's absent, since the shlib dependency of that test requires
RTLD_NEXT to function.
This allows the testsuite to be built on Cygwin, which behaves
exactly like UNIX, but doesn't have RTLD_NEXT.
On OSX both backends are built. Generally we want to use the cocoa
backend by default and in case it is not supported, i.e because
the application is not using a bundle then we should fallback
to the gtk one.
ostream_flush_cb() was calling flush_data_list_complete() with a single
element list with an item that had already been freed. This was observed
on OpenBSD where memory is overwritten with 0xdf during free():
error=0x0) at ../glib-2.58.3/gio/gdbusprivate.c:1156
1156 g_mutex_lock (&f->mutex);
(gdb) p /x *f
$74 = {mutex = {p = 0xdfdfdfdfdfdfdfdf, i = {0xdfdfdfdf, 0xdfdfdfdf}},
cond = { p = 0xdfdfdfdfdfdfdfdf, i = {0xdfdfdfdf, 0xdfdfdfdf}},
number_to_wait_for = 0xdfdfdfdfdfdfdfdf, error = 0x0}
This happened because the thread freeing the element didn't properly wait
for the asynchronous flush operation to finish.
Gnome's developer docs say: "g_cond_wait() must always be used in a loop"
https://developer.gnome.org/glib/stable/glib-Threads.html#g-cond-wait
It returns a string in the libc locale, which is not necessarily UTF-8.
Convert that to UTF-8 before returning it to the caller.
Spotted by Tomasz Miąsko.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1732
More mounts can have same mount path, but only the last one is
accessible. Thus we should always return the last matching mount from
g_unix_mount_at() and g_unix_mount_for(). This should also solve
problems with g_file_trash() on automounted filesystems, which are
caused by the recently added mount checks.
Closes: https://gitlab.gnome.org/GNOME/glib/issues/1727
instead of using a generic G_IO_ERROR_FAILED error code.
This is in line with what W32 part of the code is doing with WSAENOTSOCK.
This fix will break two tests in libsoup, which were written following
the implementation and thus expect G_IO_ERROR_FAILED when attempting to
do stuff with no-longer-valid socket descriptors.
This reverts commit 80fcb1bc26.
G_DISABLE_DEPRECATED should never be used by anybody, least of all by
GLib. We have deprecation annotations for the compiler, these days, and
they are much better suited than a macro that makes symbols appear and
disappear. The fact that gtk-doc doesn't understand the deprecation
annotations is a limitation of gtk-doc, and it's gtk-doc that ought to be
fixed.
Commit 80fcb1bc broke GStreamer, which disables old API that was
deprecated before the introduction of the deprecation annotations, but
still uses newly deprecated one, and relies on the deprecation
annotations to do their thing. It also broke libsoup, as it uses
GValueArray in its own API.
Just skip the test if the unix transport isn’t supported. This means we
get better compilation coverage, and more explicit TAP output saying
that the test is being skipped on unsupported platforms.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
The specification doesn’t explicitly say this, but it doesn’t say
otherwise, and it would be pretty weird to have an empty transport name
or key.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
No need for the `meaningless` label and some unreachable if-branches.
This introduces no functional changes.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
While gtk-doc can currently detect a link to a symbol which has been
pluralised by adding ‘s’, it can’t detect when ‘es’ is added. While
that’s being fixed, reword the documentation so the links are generated
correctly anyway.
gtk-doc fix here: https://gitlab.gnome.org/GNOME/gtk-doc/merge_requests/22
Signed-off-by: Philip Withnall <withnall@endlessm.com>
As pointed out by gtk-doc, these are all symbols which have been marked
as deprecated, but which aren’t protected by a deprecation guard. We
can’t use G_DEPRECATED_IN_* for them, as they are all non-function
symbols. Instead, wrap them in #ifndef G_DISABLE_DEPRECATED.
In some cases, we also need to wrap one or two functions which use the
deprecated types in G_DISABLE_DEPRECATED too.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
If using the --interface-info-{body,header} options to gdbus-codegen,
and the first interface to be outputted has no methods, but does have
properties or signals, an uninitialised variable would be used for the
property/signal ‘since’ values.
In other situations, the ‘since’ value for a prior method would have
been incorrectly used for the properties/signals.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
The test performs implicit autolaunching of a bus
and checks if it is connectible.
In build the test is moved from "only non-windows with have_dbus_daemon"
to "anywhere".
This is intentional: actually it doesn't execute any external
binaries on unix (so doesn't require dbus_daemon)
and now has win32 implementation.
The test has some problems that are not problems of test itself,
but are reasoned by current win32 implementation:
- since the implementation uses global win32 kernel objects
with fixed names not depending on g_get_user_runtime_dir or other context
if preexisting bus running by some other libgio-using application
the test would silently pass.
- since the implementation uses problematic time-based synchronization,
that has a race condition between opening and reading mmaped address,
the test may randomly fail (I'd not seen this in practice).
- since the implementation autolaunched process works for 3 seconds
after last client disconnects, the executed subprocess runs for 3 seconds
after test exit, maybe locking the libgio-2.0-0.dll file for that time.
This is a bit of breaking change:
After this commit the apps relying of win32 dbus autolaunching,
need to install gdbus.exe alongside with libgio-2.0-0.dll.
A new command for gdbus tool is used for running server:
gdbus.exe _win32_run_session_bus
To implement it gdbus.exe uses the same exported function
g_win32_run_session_bus that earlier was used by rundll.
So (private) ABI was not changed.
It runs the bus syncronously, exiting after inactivity timeout -
all exactly like it was runed earlier with the help of rundll32.
While private exported function may have _some_
version compatibility issues between gdbus.exe and libgio-2.0-0.dll
compiling dbus server registration logic directly into gdbus.exe
can lead to _more hidden and more complex_ compatibility issues
since the names and behaviour of syncronization objects
used to publish server address would be required compatible between
gdbus.exe and libgio-2.0-0.dll.
So using "private" exported function to call
looks like more safe behaviour.
gdbus.exe binary was selected for this task since
it has corresponding name and at least for msys2 is shippied
in same package with libgio-2.0-0.dll
turn_off_the_starting_cursor function is also kept as is,
however it is not obvious if it is still needed
(by now I failed reproducing original issue).
Explicit g_warnings added to help with possible
problematic cases for absent or incompatible gdbus.exe
Mainloop is created after successful daemon creation
Before this change the function leaked mainloop on daemon creation fail
nm_conn_to_g_conn already handles UNKNOWN like NONE (returning
G_NETWORK_CONNECTIVITY_LOCAL in both cases). So in sync_properties
we should also set new_connectivity to G_NETWORK_CONNECTIVITY_LOCAL
for both NM_CONNECTIVITY_UNKNOWN and NM_CONNECTIVITY_NONE.
This has the added benefit that when NetworkManager returns the network
connectivity is UNKNOWN, we set network_available to FALSE as it should
be. Previously, there were cases in a laptop with no network access,
that g_network_monitor_get_network_available returned true, which was
wrong and is also fixed with this commit.
g_assert_*() give more informative failure messages, and aren’t compiled
out when building with G_DISABLE_ASSERT.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
g_assert_*() give more informative failure messages, and aren’t compiled
out when building with G_DISABLE_ASSERT.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
In order to allow GLib itself to be built with G_DISABLE_ASSERT defined,
we need to explicitly undefine it when building the tests, otherwise
g_test_init() turns into an abort.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1708
g_assert_*() give more informative error messages on failure, and can’t
be disabled by G_DISABLE_ASSERT.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
This allows referencig them from more than single .c file.
Implementation moved without changes
from gdbusaddress.c to gdbusprivate.c
g_win32_run_session_bus signature also kept, so ABI unchanged.
Closes: https://gitlab.gnome.org/GNOME/glib/issues/1566
Short names were used in win32 implementation to allow launching
on installations where full path to libgio-2.0-0.dll contain spaces.
However, short names are optional on windows: so if they were disabled
that method fails - see issue linked above.
Since rundll32 doesn't support neither spaces, nor quotes in cmdline
this patch changes rundll32 argument to just .\gio-dll-name.dll
and uses the entire path directory containing gio dll as rundll32
current directory.
Added comments informing about potential subtleties discovered during
writing test for gdbusaddress on win32.
There are not known to have real-world user-visible effect,
so by now I'm only adding comments without creating issues.
Commit f975858e86 removed the NULL check in g_cancellable_cancel() by
accident which makes it crash when called with NULL.
Add the check back and add a test so this doesn't happen again.
Fixes#1710
Implement the approach suggested in
https://gitlab.gnome.org/GNOME/glib/merge_requests/276
1. Try to open O_RDWR. On success, pass that fd
2. If EACCESS => fail the trash op, we "need" read-write to successfully trash it
3. If EISDIR => re-open the fd with O_PATH, and pass that (which will fail on snap,
but verify the dir for flatpaks)
Don’t pollute the build directory with files generated by running the
test.
Note that there are still other tests in the gsettings.c test suite
which use the build directory, but fixing them is a bit more involved
than I have time for right now. This is a step in the right direction.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
res_ninit() requires the __res_state struct passed to it to be
zero-filled on FreeBSD.
Spotted and analysed by Ashish SHUKLA.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes#1697
Synchronize access to cancelled flag of cancellable, which was
previously access without synchronization in g_cancellable_is_cancelled.
Use atomic operations instead of existing global mutex, to avoid
serializing calls to g_cancellable_is_cancelled across all threads.
Ensure that source is attached to the context before it migth be used
from another thread, since otherwise operation on source are
unsynchronized and not thread-safe.
In particular there was a data race between g_source_attach and
g_source_set_ready_time (used from g_file_monitor_source_handle_event).
This essentially reverts commit
cffed58737.
The preceding two commits have fixed the test so it’s no longer flaky.
The following command gives 5000 passes in a row for me:
meson test -C /opt/gnome/build/glib/ socket-service --repeat 5000
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Fixes: #1679
It’s occasionally possible for the cancellation of the service to happen
before connection_cb() gets scheduled in the other thread. The
locking/unlocking order of mutex_712570 requires:
• test_threaded_712570(): lock mutex
• test_threaded_712570(): start wait loop
• connection_cb(): lock mutex
• test_threaded_socket_service_finalize(): unlock mutex
• test_threaded_712570(): end wait loop
• test_threaded_712570(): unlock mutex
Fix that by quitting the main loop once connection_cb() has been called
(i.e. once the server thread has received the incoming connection
request), rather than just after the client thread (main thread) has
sent a connection request.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1679
On about 1 in 3 test runs, the socket-service would fail with the
ref_count assertion in connection_cb() failing (the ref_count would be 3
rather than the expected 2).
This was happening because the GTask from
g_socket_listener_accept_socket_async() now always takes at least one
main context iteration to return a result (whereas before
6f3d57d2ee it might have taken zero), but
the ref_count can drop below 3 before the process of returning a result
starts. During the process of returning a result, the ref_count
temporarily increases again, which is what was breaking the test.
Fix this by waiting for one more main context iteration. This is a bit
of a hack, but the real fix would be to expose the outstanding_accept
boolean from GSocketService as public API (which the test can
interrogate), and that seems too much like exposing internal state.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Helps: #1679
Almost everything that needs gioenumtypes.h also needs
gobjectenumtypes.h. Fixes:
ccache cc @gio/win32/gio@win32@@giowin32@sta/gwin32filemonitor.c.obj.rsp
In file included from ../gio/win32/gwin32filemonitor.h:25:0,
from ../gio/win32/gwin32filemonitor.c:26:
../glib/glib-object.h:37:10: fatal error: gobject/gobjectenumtypes.h: No such file or directory
#include <gobject/gobjectenumtypes.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
GIO modules built with MSVC do not begin with 'lib', but they can
begin with 'gio'. Without this, you can only load GIO modules built
with MSVC that are `name.dll`, not `gioname.dll`.
Eliminate several cases of splitting sentences between multiple
translatable strings, and remove some newlines from the translatable
strings (they always need to be present, and can confuse translation, so
add them unconditionally afterwards).
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Compilers get confused when variables are initialized by a function by
taking them as reference in an out argument; this, coupled with the fact
that C does not initialize variables by default, most commonly results
in a "maybe uninitialized" compiler warning.
512e9b3b34 added a call to schedule_pending_close() in the read
callback after the reference to the worker is already gone. In case this was
the last reference to the worker this resulted in a use-after-free.
6f3d57d2ee made this more likely to happen because on connection close
the worker cancel action is now async while the reference to the worker
gets dropped right away.
Move the call to schedule_pending_close() before the unref.
Fixes#1686
When testing as root, changing the permissions of the keyfile will have
no effect on the writability since root bypasses these permissions. See
path_resolution(7). Skip the test in this case.
g_assert_*() give more informative error messages, and aren’t compiled
out when building with G_DISABLE_ASSERT.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
getsockname() returns the address that the socket was bound to.
If it was bound to INADDR_ANY, getsockname() will stubbornly return INADDR_ANY
(and someport - that one is valid).
Subsequent connection attempts to INADDR_ANY:someport will fail with winsock.
Actually, it doesn't make even sense to connect to INADDR_ANY at all
(where is the socket connecting to? To a random interface of the host?),
so this is just a straight-up change, without platform-specific ifdefing.
Use loopback instead of INADDR_ANY. To ensure that binding and creation
of INADDR_ANY is still tested, use two addresses: bind to INADDR_ANY,
but connect to loopback, with the port number that we got from the bound
address.
Use a static GQueue to form the GList of mounts by appending (which
is fast, because GQueue tracks the tail pointer of its internal GList),
then return that GList. This way we don't need to form the list
by prepending, which would have made it necessary to reverse it before
returning.
If the list is not ordered correctly, local drives in GTK places sidebar
are shown in reverse order.
The gsocketclient-slow test needs this, otherwise connect() succeeds
immeidately and the test fails, because it is checking that cancellation
works. We weren't installing it for installed tests.
It's necessary sometimes for installed tests to be able to run with a
custom environment. For example, the gsocketclient-slow test requires an
LD_PRELOADed library to provide a slow connect() (this is to be added in
a followup commit).
Introduce a variable `@env@` into the installed test template, which we
can override as necessary when generating `.test` files, to run tests
prefixed with `/usr/bin/env <LIST OF VARIABLES>`.
As the only test that requires this currently lives in `gio/tests/`, we
are only hooking this up for that directory right now. If other tests in
future require this treatment, then the support can be extended at that
point.
There's no /tmp directory on Windows.
Use g_get_tmp_dir(), and adjust the test to work with that.
The test *still* checks the basename of the new CWD, it just
doesn't need to be "tmp" anymore.
envp in spawn() functions is the *whole* environment table
for the child process. Including PATH. Thus, unless PATH is explicitly
put into that table, the process will be spawned without PATH.
Since on Windows binaries are found via PATH instead of LD_LIBRARY_PATH
or whatever, almost no program (unless installed in WINDIR, maybe)
can run without a PATH. Certainly not test programs - meson
adds bld subdirs to the PATH to make sure that test programs
use uninstalled glib at runtime.
So make sure that PATH is passed along.
Windows \r\n EOLs strike again. The test already knows about LINEEND,
so make it use LINEEND more (instead of swithcing pipes
to binary mode). This also applies to counting the bytes
read.
With winsock sending messages to NULL results in G_IO_ERROR_NOT_CONNECTED
instead of G_IO_ERROR_FAILED.
MSDN says:
WSAENOTCONN
10057
Socket is not connected.
A request to send or receive data was disallowed because the socket is not connected
and (when sending on a datagram socket using sendto) no address was supplied.
So this is a direct mapping of the implementation error.
Covering it up in the wrapper (by converting it to G_IO_ERROR_FAILED)
doesn't seem feasible or needed (no one, except for the testsuite,
really cares which unrecoverable error is returned by sendto()).
getaddrinfo() in winsock can't understand scope IDs.
There's no obvious way to fix that, short of re-implementing
that function, so disable that part of the test on Windows.
G_RESOURCE_OVERLAYS is a list of resource-path and filesystem-path pairs.
Since on Windows filesystem paths use ':', this list can't be ':'-separated
there. Fix that by making it ';'-separated on Windows. Make the parser
error clearer (we're not looking for a slash, we're looking for an absolute
path).
If a URI can't be handled by by WinHTTPVfs, it should pass that URI
along to the URI parser of the wrapped Vfs, not to its generic parser.
Theoretically, generic parser should also be able to handle URIs,
but this is subject to Vfs semantics.
In case of Windows, the wrapped Vfs is GLocalVfs, which is *local* and
treats any generic names as either file:// URIs or as filesystem
paths. It only ever treats URIs as URIs when they are passed
to its URI parser. This breaks the testsuite when g-icon GIO test passes
unhandleable sftp:// URI, and expects it to come through unmolested,
yet GLocalVfs, getting that URI as a generic parse name, treats it as
a filesystem path, and then "canonicalizes" it by prepending CWD.
Fix this by making WinHTTPVfs pass any URIs it gets to the URI parser
of the wrapped Vfs. This way unknown URIs remain URI-ish. This seems
like a reasonable things to do, since the URI parser should not be
given anything other than URIs, so there's no reason to try generic
parsing with these strings.
Closes: #875
Previously once the end of addresses was reached it would return
NULL even if it was waiting on a dns response. Now it will keep
waiting so all addresses are received.
Fixes#1680
Currently, the actual asynchronous work, represented by
asynchronous_cancellation_run_task, was over before the GCancellable
could be triggered. While that doesn't invalidate the purpose of the
test, since it's fundamentally about cancellation, it would be
nicer if the cancellation actually served some purpose instead of
being a mere formality.
https://gitlab.gnome.org/GNOME/glib/issues/1608
When calling g_socket_listener_accept_socket_async() on a
GSocketListener with multiple sockets, the accept_ready() callback is
called for the first incoming connection on each socket. It will return
success/failure for the entire accept_socket_async() GTask, and then
free the GSources for listening for incoming connections on the other
sockets in the GSocketListener. The GSources are freed when the GTask is
finalised.
However, if incoming connections arrive for multiple sockets within the
same GMainContext iteration, accept_ready() will be called multiple
times, and will call g_task_return_*() multiple times, before the GTask
is finalised. Calling g_task_return_*() multiple times is not allowed.
Propagate the first success/failure, as before, but then ignore all
subsequent incoming connections until the GTask is finalised.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Once cancelled, a GTask's callback should not only be invoked
asynchronously with respect to the creation of the task, but also with
respect to the GCancellable::cancelled handler. This is particularly
relevant in cases where the cancellation happened in the same thread
where the task is running.
Spotted by Dan Winship and Michael Catanzaro.
Closes https://gitlab.gnome.org/GNOME/glib/issues/1608
It needs investigating and fixing properly, but let’s not let it disrupt
the CI in the meantime.
Follow-up in https://gitlab.gnome.org/GNOME/glib/issues/1679.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
To make things consistent across the board as that is the WinSock2 error
code that is received by g_socket_send_message_with_timeout() when it
returns G_POLLABLE_RETURN_WOULD_BLOCK.