Previously, the code validated that child objects have a path with the
object manager strictly as a prefix. That doesn’t work in the case where
the object manager’s path is `/`. This case is not recommended, but is
supported.
If the object manager’s path is `/`, validate that child objects’ paths
are not equal to it. If they are equal to it, warn the user rather than
emitting a critical warning, since we can’t expect any users who’ve not
been compliant with the spec to instantly rework their D-Bus APIs.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2500
Emit this when we're about to spawn or DBus activate a GAppInfo. This
allows lauchers to keep the appinfo associated with a startup id.
We use a GVariant to allow for future exansion of the supplied data.
When using g_desktop_app_info_launch_uris_as_manager the "launched"
signal allows to map a desktop-startup-id to a GAppInfo. Make this
possible for DBus activation too.
Since we don't have a PID there we pass a 0. Update the signal
description accordingly.
These should be implemented by loadable IO module libraries, but are not
callable in GLib itself.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2498
This is a partial revert of commit
f378352051, as the previous commits have
silenced the AddressSanitizer warnings for `GContentType`.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2310
The function pointer casts silence the compiler and allow the code to
build (and even run in the typical case). However, when building with
control flow integrity checks, the runtime (rightfully) complains about
calling a function via a mismatched function pointer type.
In order to make xdgmime properly relocatable so that unit tests can use
it without it reading and modifying the user’s actual xdgmime files, and
without the need to call setenv() (and get tied up with thread safety
problems), add a xdg_mime_set_dirs() method to allow the dirs to be
overridden. They will still default to the values of $XDG_DATA_HOME and
$XDG_DATA_DIRS.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
Allocate an empty cache object, check cache objects for being empty
before using them.
Otherwise the code will re-read cache every 5 seconds, as NULL cache
does not trigger the code that stores mtime, which makes the cache
file appear modified/unloaded permanently.
https://bugzilla.gnome.org/show_bug.cgi?id=735696
Since returning exactly one match has special significance, don't
give up matching before we've found at least 2 types. Also, make
sure that we don't return the same mime type more than once.
Bug 541236.
If an `InterfacesRemoved` signal is received for an object which doesn’t
exist in the local map of interfaces, don’t emit a warning.
This seems to happen in the real world (see #2401). Without a trace of
the D-Bus traffic it’s not possible to know exactly what situation is
causing this, but it seems possible that the peer could disappear and
its `notify::name-owner` signal could be processed before its
`InterfacesRemoved` signal, or something similar.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2401
Relax assertion about opened registry key as it may have been removed
in the meantime between enumeration and when opening, or (more likely)
we may not have the required permissions to open the some enumerated
keys (i.e. RegOpenKeyExW fails and returns ERROR_ACCESS_DENIED).
Fixes https://gitlab.com/inkscape/inbox/-/issues/5669
Instead of calling xterm when it clearly does not exist and causes a silent error,
inform the user that the launch failed so they can take the right action.
Also added (transfer full) or (transfer none) annotations while I was at it.
This is the result of checking each `Returns:` line in these files. I’ve
only considered nullability and transferability, and not other (potentially
missing or incorrect) annotations.
Helps: #2227
If the first power-profile installed test fails (for example, because
xdg-desktop-portal isn’t available), correctly tear down the dbusmock
object, or it will cause setUp() to fail when the next test in the suite
is run.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2481
When first creating the monitor, correctly set its property value to the
value from the portal, rather than waiting for the portal value to
change to set it.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2481
We were lucky that this worked in some cases (the test is racy), but we
should actually run the condition check each loop, rather than when the
function is called.
Spotted by Martin Pitt:
96a8c02d24 (r54773831)
Let's explain the advantages of relying on GTlsConnection to perform
certificate verification.
Also, document that the issuer property is a little tricky, because the
issuer certificate might not be the certificate that actually gets used
in final certification path building. This is very unexpected to anybody
who is not an expert.
Because TLS certificate verification is extremely complex, the lookup
issuer function may be tempting to misuse even by experienced
developers. There is a notion that the issuer certificate will always be
used in the final certification path, but it's just not always true.
Trying to make security decisions based on the results of this function is
a trap, so let's document that.
It turns out that old versions of glib-networking actually reordered the
certificate chain to match the final verification path. This no longer
happens since a long time ago, because it was a buggy mess. Instead, we
rely on the TLS library to build the final verification path. Their path
building is not very good, but at least it's consistent. The point of
these doc updates is to clarify that only the TLS library can make
security decisions.
Document that HTTP requests may be performed to look up missing
certificates.
Finally, let's document that certificate verification using GTlsDatabase
cannot be as smart as certificate verification performed directly by
GTlsConnection.
g_win32_package_parser_enum_packages() reads beyond the end of a buffer
when doing a memcpy. With app verifier enabled on Windows, it causes
the application to crash on startup.
This change limits the memcpy to the size of the source string.
Fixes: #2454
This reverts commit 7aa0580cc5.
As stated in #2316, that commit was a workaround to allow gnome-keyring
and msmtp to continue to get their session bus address from
`DBUS_SESSION_BUS_ADDRESS`, even though they’re `AT_SECURE`. The timeout
on that workaround has expired so that commit is now being reverted.
Fixes: #2316
You need to separate the first entry in the list from the preceding
paragraph, and you should add a space before the enumerating symbol.
GTK-Doc accepts a very lax Markdown syntax, but any other tool parsing
our documentation will likely fail.
The value should be initialized to NULL before calling
g_win32_registry_key_get_value_w(), to ensure that cleanup
can be done unconditionally afterward.
To ensure that the watch is properly re-set every time, call
watch_keys() from the watch callback. Previously the watch was only
renewed after a data update was done in a worker thread, which made
no sense, since the update function was implemented in such a way
that it can (and should) be re-triggered on each key change, until
the changes stop coming, and that can only happen if we renew
the registry watcher right away.
If a key watch is renewed from the key watch callback, it results
in the callback being NULL, since we clear it after we call it.
Rearrange the function to make sure that the changes done by the
callback function are preserved properly.
This function can, in fact, return STATUS_SUCCESS. We shouldn't
assert that it doesn't.
For now interpret it just like STATUS_PENDING (i.e. APC will be called),
see how it goes (it isn't documented how the function behaves in this
case, we have to play it by ear).
Note that while we *can* use a better-documented RegNotifyChangeKeyValue() here,
it communicates back to us via event objects, which means that the registry
watcher would have to interact with the main loop directly and insert its
events (plural; one event per key) there. That would make the API more complicated.
Whereas the internal NT function communicates by calling an APC - we're good
as long as something somewhere puts the thread in alertable state.
When attempting to test Windows support for building libadwaita, since we are
using multiple GResource files, one would hit linker errors where multiple
definitions of the following symbols have been defined, when
glib-compile-resources was invoked without manual register:
resource_constructor_wrapper
resource_destructor_constructor
_arrayresource_constructor
_arrayresource_destructor
In order to avoid that, just prefix the definitions of resource_constructor
and resource_destructor, like what we do when --manual-register is used, with
what we pass in with --c-name so that we ensure that we do not end up in such
name collisions.
Port all existing calls in GLib to the new API so that they can receive
more detailed error information (although none of them actually make use
of it at the moment).
This also serves to test the new API better through use.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #203
The `g_file_trash` function fails with the `Unable to find or create trash
directory` error when the global `.Trash` directory exists. This is because
the commit 7f2af262 introduced the `gboolean success` variable to signalize
the detection of the trash folder, but didn't set it in all code branches.
Since for a time this variable was not initialized the bug wasn't visible
when the trash folder existed. The bug became effective after the `success`
variable was initialized with `FALSE` by the commit c983ded0. Let's explicitly
set the `success` variable in all branches to fix the global trash dir
detection.
Fixes: https://gitlab.gnome.org/GNOME/glib/-/issues/2439
The function which calls `SetFileTime()` works with seconds and
nanosecond, but the functions which call it are doing so with seconds
and microseconds.
Fix them so they convert to nanoseconds first.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
The code appears to be dealing with time in units of 100ns, not 100µs,
so name the variable accordingly.
The rest of the arithmetic in that function appears consistent and
correct.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
The modification time test creates a file, gets the modification time in
seconds, then gets the modification time in microseconds and assumes
that the difference between the two has to be above 0.
As rare as this may be, it can happen:
$ stat g-file-info-test-50A450 -c %y
2021-07-06 18:24:56.000000767 +0100
Change the test to simply assert that the difference not negative to
handle this case.
This is necessary when building glib with icecc. Icecc splits the build
process into two parts. The file is locally preprocessed with
-fdirectives-only to resolve any includes. This adds linemarkers to the
intermediate file. Without the new-line at the end of the file this:
#include "gconstructor_as_data.h"
#include "glib/glib-private.h"
Is turned into this:
const char gconstructor_code[] = "...";# 1 "glib/glib-private.h"
...
The result is a compile error:
In file included from ../glib/gio/glib-compile-resources.c:45:
gio/gconstructor_as_data.h:1: error: stray '#' in program
gio/gconstructor_as_data.h:1: error: expected identifier or '(' before numeric constant
In file included from ../glib/glib/glib-private.h:22,
from gio/gconstructor_as_data.h:2,
from ../glib/gio/glib-compile-resources.c:45:
../glib/glib/gwakeup.h:27:1: error: unknown type name 'GWakeup'
../glib/glib/gwakeup.h:28:42: error: unknown type name 'GWakeup'
../glib/glib/gwakeup.h:30:42: error: unknown type name 'GWakeup'
../glib/glib/gwakeup.h:32:42: error: unknown type name 'GWakeup'
../glib/glib/gwakeup.h:33:42: error: unknown type name 'GWakeup'
In file included from gio/gconstructor_as_data.h:2,
from ../glib/gio/glib-compile-resources.c:45:
../glib/glib/glib-private.h:98:3: error: unknown type name 'GWakeup'
../glib/glib/glib-private.h:99:58: error: unknown type name 'GWakeup'
../glib/glib/glib-private.h💯58: error: unknown type name 'GWakeup'
../glib/glib/glib-private.h:102:58: error: unknown type name 'GWakeup'
../glib/glib/glib-private.h:103:58: error: unknown type name 'GWakeup'
In file included from gio/gconstructor_as_data.h:2,
from ../glib/gio/glib-compile-resources.c:45:
../glib/glib/glib-private.h:164:53: warning: file "../glib/gio/glib-compile-resources.c" linemarker ignored due to incorrect nesting
To avoid this, generate gconstructor_as_data.h with a new-line at the end
of the file.
Signed-off-by: Michael Olbrich <m.olbrich@pengutronix.de>
This helps to void deadlocks when two processes call interfaces on each
other one of them being org.freedesktop.DBus.ObjectManager.
Signed-off-by: Guido Günther <agx@sigxcpu.org>
The current code is unsafe to use from multiple threads at once.
GIOStream functions like this are supposed to be semi-threadsafe. It's
allowed for them to be called on both a reader thread and a writer
thread at the same time. Of course, it's still tricky and dangerous,
because it's only *really* threadsafe if the handshake has finished,
and API users have no plausible way to know that because the API
does not require performing an explicit handshake operation. But that's
a glib-networking problem. We can at least avoid the most obvious
threadsafety issue here in the API layer.
Note that we'll need to implement the new vfunc in glib-networking for
this to actually work.
Fixes#2393
The documentation for `g_bus_watch_name()` implies that the
`GDestroyNotify` for the user data will be called in the current thread
default `GMainContext`. Currently, it could be called in any thread, as
`client_unref()` can be called in any thread.
Fix that by deferring it to an idle source if `client_unref()` finalises
the `Client` object in a different thread.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
These were missing from the test before the previous commit ported from
`GMainLoop` to `GMainContext`.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
It makes combination exit conditions a lot easier than when using
`g_main_loop_quit()` from different callbacks.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
The first sentence incorrectly said that it checked the type of the
value, and then the second sentence explicitly said it was a programmer
error to give a value of the wrong type.
According to the code, the second sentence is correct.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2425
WebKit wants these private key properties to be readable in order to
implement a deserialization function. Currently they are read-only
because at the time GTlsCertificate was originally designed, the plan
was to support PKCS#11-backed private keys: private keys that are stored
on a smartcard, where the private key is completely unreadable. The
design goal was to support both memory-backed and smartcard-backed
private keys with the same GTlsCertificate API, abstracting away the
implementation differences such that code using GTlsCertificate doesn't
need to know the difference.
The original PKCS#11 implementation was never fully baked and at some
point in the past I deleted it all. It has since been replaced with a
new implementation, including a GTlsCertificate:private-key-pkcs11-uri
property, which is readable. So our current API already exposes the
differences between normal private keys and PKCS#11-backed private keys.
The point of making the private-key and private-key-pem properties
write-only was to avoid exposing this difference.
Do we have to make this API function readable? No, because WebKit could
be just as well served if we were to expose serialize and deserialize
functions instead. But WebKit needs to support serializing and
deserializing the non-private portion of GTlsCertificate with older
versions of GLib anyway, so we can do whatever is nicest for GLib. And I
think making this property readable is nicest, since the original design
reason for it to not be readable is now obsolete. The disadvantage to
this approach is that it's now possible for an application to read the
private-key or private-key-pem property, receive NULL, and think "this
certificate must not have a private key," which would be incorrect if
the private-key-pkcs11-uri property is set. That seems like a minor
risk, but it should be documented.
On Unix platforms, wait() and friends yield an integer that encodes
how the process exited. Confusingly, this is usually not the same as
the integer passed to exit() or returned from main(): conceptually it's
an integer encoding of this tagged union:
enum { EXITED, SIGNALLED, ... } tag;
union {
int exit_status; /* if EXITED */
struct {
int terminating_signal;
bool core_dumped;
} terminating_signal; /* if SIGNALLED */
...
} detail;
Meanwhile, on Windows, wait statuses and exit statuses are
interchangeable.
I find that it's clearer what is going on if we are consistent about
referring to the result of wait() as a "wait status", and the value
passed to exit() as an "exit status".
GSubprocess already gets this right: g_subprocess_get_status() returns
the wait status, while g_subprocess_get_exit_status() genuinely returns
the exit status. However, the GSpawn family of APIs has tended to
conflate the two.
Confusingly, g_spawn_check_exit_status() has always checked a wait
status, and it would not be correct to pass an exit status to it; so
let's deprecate it in favour of g_spawn_check_wait_status(), which
does the same thing that g_spawn_check_exit_status() always did.
Code that needs backwards-compatibility with older GLib can use:
#if !GLIB_CHECK_VERSION(2, 69, 0)
#define g_spawn_check_wait_status(x) (g_spawn_check_exit_status (x))
#endif
Signed-off-by: Simon McVittie <smcv@collabora.com>
Confusingly, g_spawn_check_exit_status() takes a wait status, not an
exit status, so passing g_subprocess_get_exit_status() to it is
incorrect (although both encodings happen to use 0 to encode success
and a nonzero value to encode failure, so in practice this probably
had the desired effect).
Signed-off-by: Simon McVittie <smcv@collabora.com>
Following on from the previous commit, some explicit
`g_main_context_wakeup()` calls were missing from the test code which
only uses `GMainContext`.
Add them, and also add some assertions to check that these functions are
being called in the expected thread (as the code comments say).
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
This is a bit of a compromise. Since the option parsing in
`GApplication` is built on `GOptionContext`, there’s no way to
reliably indicate that a given option was passed by the user, other than
by its value changing. If the default value is zero, but the user
explicitly passed zero, nothing changes, so it’s not obvious that the
option was explicitly provided.
When just `GOptionContext` is being used, this is fine, as that’s
obvious what will happen from the way the API is built. With
`GApplication::handle-local-options`, though, the `GVariantDict`
provided by GLib to the callback claims to only contain the values of
the options provided by the user, and no defaults.
It’s not actually possible for GLib to do that reliably.
Previously, GLib was dropping all numeric values which were zero valued
(i.e. the defaults), as they *could* have been the defaults. It seems
like a slightly better behaviour to instead *not* drop those numeric
values, and err on the side of reporting some defaults as user-provided
(even if they weren’t) rather than dropping some user-provided values
which happen to be the defaults.
This adds a test for the case of parsing a double; the cases for
integers are analogous.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2329
The tests in `gdbus-names.c` use a mixture of `GMainLoop` and iterating
a `GMainContext` directly. Some of the helper functions based around the
`OwnNameData` struct use the `loop` `GMainLoop` even when called from
tests like `watch_with_different_context()` which themselves use
`GMainContext` directly.
Thus, it’s possible for the `GMainLoop` to not be running, while the
test is iterating on `g_main_context_iteration()`. In this case,
`g_main_loop_quit()` is a no-op and will not wake up the `GMainContext`.
This causes the test to livelock in around 1 in 1200 test runs.
Fix this by adding an explicit `g_main_context_wakeup()` call after each
`g_main_loop_quit()` call. A more comprehensive fix would be to port all
the tests in this file to iterating `GMainContext` directly, and drop
all the `GMainLoop` usage, but I don’t have time for that right now.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
If `g_file_monitor_source_dispatch()` drops the last reference to its
`GLocalFileMonitor`, a deadlock will occur, because disposing the
`GLocalFileMonitor` causes synchronous disposal of the
`GFileMonitorSource`, and hence an attempt to re-lock the already-locked
mutex in the `GFileMonitorSource`.
Fix that by dropping the reference to the `GLocalFileMonitor` after
unlocking.
Diagnosed by Ting-Wei Lan. The bug was originally introduced by me in
commit 592a13b483.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Relax the requirement for the test to only be compiled/run under gcc,
since a version of LLVM was released which supports `--add-symbol`.
`objcopy` should be overrideable to be `llvm-objcopy` by using a machine
file as per https://mesonbuild.com/Machine-files.html#binaries.
Suggested and tested by Grigory Vasilyev.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2423
Clarify that the terms ‘GUID’ and ‘UUID’ are used interchangeably in the
context of D-Bus, and that neither of them are an RFC 4122 UUID.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Update several links to allow the remote to use its configured default
branch name, rather than specifying `master` as the default branch name.
This will help avoid breakage if any of these projects rename their
default branch in the future.
Fix a few of the links where they were hitting redirects or had moved.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2348
Since commit 87e19535fe, the ETag check when writing out a file through
a symlink (following the symlink) has been incorrectly using the ETag
value of the symlink, rather than the target file. This is incorrect
because the ETag should represent the file content, not its metadata or
links to it.
Fix that, and add a unit test.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2417
This adds g_tls_connection_get_protocol_version(),
g_tls_connection_get_ciphersuite_name(), and DTLS variants. This will
allow populating TLS connection information in the WebKit web inspector.
This is WIP because we found it's not quite possibly to implement
correctly with GnuTLS. See glib-networking!151.
This is the result of checking each `Returns:` line in these files. I’ve
only considered nullability and not other (potentially missing or
incorrect) annotations.
Including suggestions by Simon McVittie.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Helps: #2227
In a PKCS#11 operation there are multiple types of PINs possibly
needed and these flags add a way to expose them to the user.
This design exactly matches gnutls' gnutls_pin_flag_t API.
This changeset exposes
* `not-valid-before`
* `not-valid-after`
* `subject-name`
* `issuer-name`
on GTlsCertificate provided by the underlying TLS Backend.
In order to make use of these changes,
see the related [glib-networking MR][glib-networking].
This change aims to help populate more of the [`Certificate`][wk-cert]
info in the WebKit Inspector Protocol on Linux.
This changeset stems from work in Microsoft Playwright to [add more info
into its HAR capture][pw] generated from the Inspector Protocol events
and will bring feature parity across WebKit platforms.
[wk-cert]: 8afe31a018/Source/JavaScriptCore/inspector/protocol/Security.json
[pw]: https://github.com/microsoft/playwright/pull/6631
[glib-networking]: https://gitlab.gnome.org/GNOME/glib-networking/-/merge_requests/156
The `GApplication` must be registered before calling
`g_application_mark_busy()`. Document that, and add a guard.
The same is true for `g_application_unmark_busy()`, but the existing
documentation and guard for `busy_count > 0` are enough.
For the reasons given in the new bit of documentation, GDBusProxy should
not be used for connecting to stateless D-Bus services which may be
restarted at any point.
Signed-off-by: Philip Withnall <withnall@endlessm.com>
https://gitlab.gnome.org/GNOME/glib/issues/1036
Include the base URI in the `g_test_bug()` calls instead. This resolves
inconsistencies between the old bug base (bugzilla.gnome.org) and the
new bug base (gitlab.gnome.org). It also has the advantage that the URI
passed to `g_test_bug()` is now clickable in the code editor, rather
than being split across two locations.
See https://gitlab.gnome.org/GNOME/glib/-/merge_requests/275#note_303175
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Since commit ab285899a6 ('gdbusconnection: Document main context
iteration for unsubscript'), we document when the user is guaranteed
that all resources are gone after g_dbus_connection_signal_unsubscribe().
This is not merely an implementation detail, it's something that the
user needs to be able to rely on. It is good that this is documented.
However, libnm does something different ([1]). It registers to several D-Bus
signals without providing a GDestroyNotify. After unsubscription, it schedules
another idle action with lower priority and uses that to know when
cleanup is complete. I think this is a useful alternative and should
also be guaranteed and documented to work.
Also note that this isn't just some implementation detail that currently
happens to work. GDBusConnection tightly integrates with GMainContext and it
works by scheduling idle sources with G_PRIORITY_DEFAULT priority. It needs to
schedule all events with this same priority, otherwise the ordering is not
preserved. At this point, with GDBusConnection working this way, this is no longer
something that can reasonably be any different. It's how GDBusConnection fundamentally
works, and a user must be able to rely on that. As such, this new promise isn't
something that we would want to break in the future.
Thus document it.
[1] a55c10c6cb/src/libnm-client-impl/nm-client.c (L7918)
This fixes a bug where the family flag was ignored in lookup_data_new,
causing the resolver to call getaddrinfo with no hints set when clearly
the family hint should have been set.
gio/tests/unix-streams.c: In function ‘test_write_async_wouldblock’:
gio/tests/unix-streams.c:692:17: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint’ {aka ‘int’}
692 | for (i = 0; i < 4 * pipe_capacity; i++)
| ^
gio/tests/unix-streams.c: In function ‘test_writev_async_wouldblock’:
gio/tests/unix-streams.c:780:17: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint’ {aka ‘int’}
780 | for (i = 0; i < 4 * pipe_capacity; i++)
| ^
An application that has been shut down is still marked as registered
even if its implementation has been already destroyed.
This may lead to unguarded crashes when calling functions that have
assumptions for being used with registered applications.
So, when an application is registered, mark it as unregistered just
before destroying its implementation and after being shut down, so that
we follow the registration process in reversed order.
Added tests
gio/tests/socket-common.c: In function ‘socket_address_from_string’:
gio/tests/socket-common.c:50:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’
50 | for (i = 0; i < G_N_ELEMENTS (unix_socket_address_types); i++)
| ^
gio/tests/gnotification-server.c: In function ‘g_notification_server_bus_acquired’:
gio/tests/gnotification-server.c:224:3: error: missing initializer for field ‘padding’ of ‘GDBusInterfaceVTable’ {aka ‘const struct _GDBusInterfaceVTable’}
224 | };
| ^
gio/tests/gdbus-proxy.c: In function ‘strv_equal’:
gio/tests/gdbus-proxy.c:158:32: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint’ {aka ‘int’}
158 | res = g_strv_length (strv) == count;
| ^~
gio/gkeyfilesettingsbackend.c: In function ‘convert_path’:
gio/gkeyfilesettingsbackend.c:155:15: warning: comparison of integer
expressions of different signedness: ‘gsize’ {aka ‘long unsigned int’}
and ‘gint’ {aka ‘int’}
155 | if (key_len < kfsb->prefix_len ||
| ^
gio/tests/gsettings.c: In function ‘strv_set_equal’:
gio/tests/gsettings.c:2268:41: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint’ {aka ‘int’}
2268 | res = g_strv_length ((gchar**)strv) == count;
| ^~
gio/tests/gdbus-testserver.c:806:1: error: missing initializer for field ‘padding’ of ‘GDBusInterfaceVTable’ {aka ‘const struct _GDBusInterfaceVTable’}
806 | };
| ^
In file included from gio/gio.h:53,
from gio/tests/gdbus-testserver.c:1:
gdbusconnection.h:395:12: note: ‘padding’ declared here
395 | gpointer padding[8];
| ^~~~~~~
gio/tests/gdbus-testserver.c: In function ‘handle_method_call’:
gio/tests/gdbus-testserver.c:334:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
334 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:343:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
343 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:352:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
352 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:361:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
361 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:370:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
370 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:379:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
379 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:388:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
388 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:397:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
397 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/gdbus-testserver.c:406:23: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
406 | for (i = 0; i < n_elts; i++)
| ^
gio/tests/mimeapps.c: In function ‘strv_equal’:
gio/tests/mimeapps.c:31:32: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint’ {aka ‘int’}
31 | res = g_strv_length (strv) == count;
| ^~
gio/tests/proxy-test.c: In function ‘do_echo_test’:
gio/tests/proxy-test.c:855:25: error: comparison of integer expressions of different signedness: ‘gssize’ {aka ‘long int’} and ‘gsize’ {aka ‘long unsigned int’}
855 | for (total = 0; total < nwrote; total += nread)
| ^
gio/tests/file.c: In function ‘written_cb’:
gio/tests/file.c:358:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘size_t’ {aka ‘long unsigned int’}
358 | if (data->pos < strlen (data->data))
| ^
gio/tests/gdbus-test-codegen.c: In function ‘check_object_manager’:
gio/tests/gdbus-test-codegen.c:2344:20: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘int’
2344 | if (om_signal_id != -1)
| ^~
gio/tests/testfilemonitor.c: In function ‘check_expected_events’:
gio/tests/testfilemonitor.c:124:39: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘gsize’ {aka ‘long unsigned int’}
124 | for (i = 0, li = 0, l = recorded; i < n_expected && l != NULL;)
| ^
gio/tests/socket.c: In function ‘test_get_available’:
gio/tests/socket.c:1696:53: error: comparison of integer expressions of different signedness: ‘gssize’ {aka ‘long int’} and ‘long unsigned int’
1696 | if (g_socket_get_available_bytes (server) > sizeof (data))
| ^
gio/tests/gdbus-export.c:130:1: error: missing initializer for field ‘properties’ of ‘GDBusInterfaceInfo’ {aka ‘const struct _GDBusInterfaceInfo’}
130 | };
| ^
In file included from gio/gio.h:57,
from gio/tests/gdbus-export.c:21:
gio/gdbusintrospection.h:156:25: note: ‘properties’ declared here
156 | GDBusPropertyInfo **properties;
| ^~~~~~~~~~
...
However, GLib still can’t guarantee to do rate limiting, as the type of
rate limiting which is appropriate depends on what tasks are being run,
and the GTask thread pool is shared between all tasks (of many different
types) in a process space.
Signed-off-by: Philip Withnall <pwithnall@endlessos.org>
Fixes: #2368
gio/tests/actions.c: In function ‘strv_set_equal’:
gio/tests/actions.c:177:41: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint’ {aka ‘int’}
177 | res = g_strv_length ((gchar**)strv) == count;
| ^~
gio/tests/actions.c: In function ‘test_parse_detailed’:
gio/tests/actions.c:473:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
473 | for (i = 0; i < G_N_ELEMENTS (testcases); i++)
| ^
gio/tests/actions.c: In function ‘test_entries’:
gio/tests/actions.c:375:5: error: missing initializer for field ‘parameter_type’ of ‘GActionEntry’ {aka ‘const struct _GActionEntry’}
375 | { "foo", activate_foo },
| ^
In file included from gio/gio.h:31,
from gio/tests/actions.c:1:
gio/gactionmap.h:63:16: note: ‘parameter_type’ declared here
63 | const gchar *parameter_type;
| ^~~~~~~~~~~~~~
...
gio/tests/gdbus-peer-object-manager.c: In function ‘mock_interface_get_vtable’:
gio/tests/gdbus-peer-object-manager.c:111:3: error: missing initializer for field ‘padding’ of ‘GDBusInterfaceVTable’ {aka ‘struct _GDBusInterfaceVTable’}
111 | };
| ^
gio/tests/network-address.c: In function ‘main’:
gio/tests/network-address.c:1194:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1194 | for (i = 0; i < G_N_ELEMENTS (host_tests); i++)
| ^
gio/tests/network-address.c:1201:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1201 | for (i = 0; i < G_N_ELEMENTS (uri_tests); i++)
| ^
gio/tests/network-address.c:1208:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1208 | for (i = 0; i < G_N_ELEMENTS (address_tests); i++)
| ^
gio/tests/network-address.c:1215:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1215 | for (i = 0; i < G_N_ELEMENTS (address_tests); i++)
| ^
gio/tests/gsubprocess.c: In function ‘test_communicate_async’:
gio/tests/gsubprocess.c:774:3: error: missing initializer for field ‘running’ of ‘TestAsyncCommunicateData’
774 | TestAsyncCommunicateData data = { flags, 0, };
| ^~~~~~~~~~~~~~~~~~~~~~~~
gio/tests/gsubprocess.c: In function ‘test_communicate_utf8_async’:
gio/tests/gsubprocess.c:1025:3: error: missing initializer for field ‘running’ of ‘TestAsyncCommunicateData’
1025 | TestAsyncCommunicateData data = { flags, 0, };
| ^~~~~~~~~~~~~~~~~~~~~~~~
gio/tests/gsubprocess.c: In function ‘test_communicate_utf8_cancelled_async’:
gio/tests/gsubprocess.c:1058:3: error: missing initializer for field ‘running’ of ‘TestAsyncCommunicateData’
1058 | TestAsyncCommunicateData data = { flags, 0, };
| ^~~~~~~~~~~~~~~~~~~~~~~~
gio/tests/gsubprocess.c: In function ‘test_communicate_utf8_async_invalid’:
gio/tests/gsubprocess.c:1202:3: error: missing initializer for field ‘running’ of ‘TestAsyncCommunicateData’
1202 | TestAsyncCommunicateData data = { flags, 0, };
| ^~~~~~~~~~~~~~~~~~~~~~~~
gio/tests/converter-stream.c: In function ‘g_expander_converter_convert’:
gio/tests/converter-stream.c:128:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
128 | for (i = 0; i < block_size; i++)
| ^
gio/tests/converter-stream.c: In function ‘g_compressor_converter_convert’:
gio/tests/converter-stream.c:234:23: error: comparison of integer expressions of different signedness: ‘long int’ and ‘gsize’ {aka ‘long unsigned int’}
234 | if (in_end - in < block_size)
| ^
gio/tests/converter-stream.c:244:21: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
244 | for (i = 0; i < block_size; i++)
| ^
gio/tests/converter-stream.c:257:33: error: comparison of integer expressions of different signedness: ‘long int’ and ‘gsize’ {aka ‘long unsigned int’}
257 | if (v == 0 && in_end - in == block_size && (flags & G_CONVERTER_INPUT_AT_END) == 0)
| ^~
gio/tests/converter-stream.c: In function ‘test_expander’:
gio/tests/converter-stream.c:356:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’
356 | for (i = 0; i < sizeof(unexpanded_data); i++)
| ^
gio/tests/converter-stream.c: In function ‘test_compressor’:
gio/tests/converter-stream.c:445:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
445 | for (i = 0; i < expanded_size; i++)
| ^
gio/tests/converter-stream.c:454:16: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
454 | g_assert (i == expanded_size -1);
| ^~
gio/tests/converter-stream.c: In function ‘test_converter_pollable’:
gio/tests/converter-stream.c:1077:17: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
1077 | for (i = 0; i < expanded_size; i++)
| ^
gio/tests/converter-stream.c:1086:16: error: comparison of integer expressions of different signedness: ‘int’ and ‘gsize’ {aka ‘long unsigned int’}
1086 | g_assert (i == expanded_size -1);
| ^~
The code did not handle EOF (0 byte read) correctly. This can e.g. cause
an infinite loop if an incorrect socks proxy is configured.
Add the appropriate checks and return an G_IO_ERROR_CONNECTION_CLOSED
error if EOF is encountered.
gio/tests/converter-stream.c: In function ‘main’:
gio/tests/converter-stream.c:1220:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1220 | for (i = 0; i < G_N_ELEMENTS (compressor_tests); i++)
| ^
gio/tests/converter-stream.c:1223:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1223 | for (i = 0; i < G_N_ELEMENTS (truncation_tests); i++)
| ^
gio/tests/converter-stream.c:1226:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
1226 | for (i = 0; i < G_N_ELEMENTS (charset_tests); i++)
| ^
gio/tests/contenttype.c: In function ‘test_tree’:
gio/tests/contenttype.c:337:17: error: comparison of integer expressions of different signedness: ‘gint’ {aka ‘int’} and ‘long unsigned int’
337 | for (i = 0; i < G_N_ELEMENTS (tests); i++)
| ^
gio/tests/contexts.c: In function ‘test_context_specific_emit’:
gio/tests/contexts.c:379:21: error: comparison of integer expressions of different signedness: ‘guint’ {aka ‘unsigned int’} and ‘gint32’ {aka ‘int’}
379 | for (i = 0; i < g_test_rand_int_range (1, 5); i++)
| ^
gio/tests/contexts.c:383:55: error: comparison of integer expressions of different signedness: ‘int’ and ‘guint’ {aka ‘unsigned int’}
383 | while (g_atomic_int_get (&observed_values[i]) != n)
| ^~
gio/tests/contexts.c:387:41: error: comparison of integer expressions of different signedness: ‘gint64’ {aka ‘long int’} and ‘guint64’ {aka ‘long unsigned int’}
387 | if (g_get_monotonic_time () > expiry)
| ^
gio/gsettings-tool.c: In function ‘gsettings_list_children’:
gio/gsettings-tool.c:199:30: error: comparison of integer expressions of different signedness: ‘size_t’ {aka ‘long unsigned int’} and ‘gint’ {aka ‘int’}
199 | if (strlen (children[i]) > max)
| ^
gio/gunixsocketaddress.c: In function ‘g_unix_socket_address_to_native’:
gio/gunixsocketaddress.c:217:15: error: comparison of integer expressions of different signedness: ‘gsize’ {aka ‘long unsigned int’} and ‘gssize’ {aka ‘long int’}
217 | if (destlen < socklen)
| ^
If this g_return_val_if_fail() is ever hit, then we leak arguments.
This is not very important because if your code hits
g_return_val_if_fail() you are invoking undefined behavior, a rather
more serious problem, but let's replace it with g_critical() to be
robust.
This includes a small behavior change: it returns 1 rather than 0 in
this error case.
Found by Coverity.
This function can cause significant delays when the mounted volume
is disconnected or just weird. Use IExtractIconW::GetIconLocation()
instead.
Theoretically, this should require COM to be initialized, but in my tests
this code worked just fine without calling CoInitializeEx().
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