Re: [PATCH] Make xmalloc and xrealloc thread-safe

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, Mar 24, 2010 at 21:22, Nicolas Pitre <nico@xxxxxxxxxxx> wrote:
> By providing a hook for the routine responsible for trying to free some
> memory on malloc failure, we can ensure that the  called routine is
> protected by the appropriate locks when threads are in play.
>
> The obvious offender here was pack-objects which was calling xmalloc()
> within threads while release_pack_memory() is not thread safe.
>
> Signed-off-by: Nicolas Pitre <nico@xxxxxxxxxxx>
> ---
>
> On Wed, 24 Mar 2010, Shawn Pearce wrote:
>
>> On Wed, Mar 24, 2010 at 11:54 AM, Nicolas Pitre <nico@xxxxxxxxxxx> wrote:
>> > Another solution could be for xmalloc() to use a function pointer for
>> > the method to use on malloc error path, which would default to a
>> > function calling release_pack_memory(size, -1).  Then pack-objects.c
>> > would override the default with its own to acquire the read_mutex around
>> > the call to release_pack_memory().  That is probably the easiest
>> > solution for now.
>>
>> Yea, that sounds like the most reasonable solution right now.
>
> So here it is.
>
> Note: there was a dubious usage of fd when calling release_pack_memory()
> in xmmap() which is now removed.
>
> diff --git a/builtin/pack-objects.c b/builtin/pack-objects.c
> index 9780258..65f797f 100644
> --- a/builtin/pack-objects.c
> +++ b/builtin/pack-objects.c
> @@ -1522,6 +1522,13 @@ static void find_deltas(struct object_entry **list, unsigned *list_size,
>
>  #ifndef NO_PTHREADS
>
> +static void try_to_free_from_threads(size_t size)
> +{
> +       read_lock();
> +       release_pack_memory(size, -1);
> +       read_unlock();
> +}
> +

Will this really work in all cases? In the find_deltas -> try_delta ->
read_sha1_file -> ... -> xmalloc call path, the mutex is already
locked when we get to xmalloc. As the mutex is of the default type
(NULL is passed as the mutex attribute argument to
pthread_mutex_init), it is undefined behaviour to lock the mutex again
(see http://www.opengroup.org/onlinepubs/007908799/xsh/pthread_mutexattr_gettype.html
)

I just realised that builtin/grep.c also needs a fix for its use of xmalloc.

- Fredrik
--
To unsubscribe from this list: send the line "unsubscribe git" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Kernel Development]     [Gcc Help]     [IETF Annouce]     [DCCP]     [Netdev]     [Networking]     [Security]     [V4L]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Linux SCSI]     [Fedora Users]