Ошибка неявная декларация функции

My compiler (GCC) is giving me the warning:

warning: implicit declaration of function

Why is it coming?

Peter Mortensen's user avatar

asked Dec 9, 2011 at 3:49

Angus's user avatar

2

You are using a function for which the compiler has not seen a declaration («prototype«) yet.

For example:

int main()
{
    fun(2, "21"); /* The compiler has not seen the declaration. */       
    return 0;
}

int fun(int x, char *p)
{
    /* ... */
}

You need to declare your function before main, like this, either directly or in a header:

int fun(int x, char *p);

answered Dec 9, 2011 at 3:50

cnicutar's user avatar

cnicutarcnicutar

178k25 gold badges365 silver badges392 bronze badges

15

The right way is to declare function prototype in header.

Example

main.h

#ifndef MAIN_H
#define MAIN_H

int some_main(const char *name);

#endif

main.c

#include "main.h"

int main()
{
    some_main("Hello, Worldn");
}

int some_main(const char *name)
{
    printf("%s", name);
}

Alternative with one file (main.c)

static int some_main(const char *name);

int some_main(const char *name)
{
    // do something
}

VLL's user avatar

VLL

9,5611 gold badge28 silver badges54 bronze badges

answered Dec 3, 2014 at 14:26

Faizal Pribadi's user avatar

When you do your #includes in main.c, put the #include reference to the file that contains the referenced function at the top of the include list.
e.g. Say this is main.c and your referenced function is in «SSD1306_LCD.h»

#include "SSD1306_LCD.h"    
#include "system.h"        #include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h>       // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h"  // This has the 'BYTE' type definition

The above will not generate the «implicit declaration of function» error, but below will-

#include "system.h"        
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h>       // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h"     // This has the 'BYTE' type definition
#include "SSD1306_LCD.h"    

Exactly the same #include list, just different order.

Well, it did for me.

answered Nov 9, 2016 at 12:04

tomc's user avatar

tomctomc

1111 silver badge2 bronze badges

0

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

answered Feb 8, 2020 at 12:48

Poussy's user avatar

When you get the error: implicit declaration of function it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname and look at the SYNOPSIS section at the top, as this section will list any header files that need to be included. Or try http://linux.die.net/man/ This is the online man pages they are hyperlinked and easy to search.
Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,

You are using a function for which the compiler has not seen a
declaration («prototype») yet.

answered Nov 26, 2015 at 7:59

Sal's user avatar

If you have the correct headers defined & are using a non GlibC library (such as Musl C) gcc will also throw error: implicit declaration of function when GNU extensions such as malloc_trim are encountered.

The solution is to wrap the extension & the header:

#if defined (__GLIBC__)
  malloc_trim(0);
#endif

answered Aug 28, 2015 at 23:05

Stuart Cardall's user avatar

2

This error occurs because you are trying to use a function that the compiler does not understand. If the function you are trying to use is predefined in C language, just include a header file associated with the implicit function.
If it’s not a predefined function then it’s always a good practice to declare the function before the main function.

answered Aug 2, 2021 at 11:31

Ndaruga's user avatar

Don’t forget, if any functions are called in your function, their prototypes must be situated above your function in the code. Otherwise, the compiler might not find them before it attempts to compile your function. This will generate the error in question.

Peter Mortensen's user avatar

answered Dec 15, 2020 at 9:23

Chris's user avatar

ChrisChris

192 bronze badges

1

The GNU C compiler is telling you that it can find that particular function name in the program scope. Try defining it as a private prototype function in your header file, and then import it into your main file.

Peter Mortensen's user avatar

answered Jul 26, 2022 at 22:19

Gabriel soft's user avatar

1

Здравствуйте.

Подскажите, пожалуйста, почему компилятор выбрасывает warning при использовании read и write?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
...
n = read(newsockfd, &buffer, (size_t *) tmp_size);
...
n = write(newsockfd, "Hi!", (size_t *) 3);
...

gcc -Wall -o "server" "server.c"
server.c: In function ‘main’:
server.c:74:5: warning: implicit declaration of function ‘read’ [-Wimplicit-function-declaration]
server.c:85:5: warning: implicit declaration of function ‘write’ [-Wimplicit-function-declaration]
Compilation finished successfully.

Из перевода понятно, что произошла неявная декларация функции. Получается, что у меня не хватает какого-то includ’a?

задан 19 апр 2013 в 18:50

DEN's user avatar

1

Это особенность С компилятора. Он может игнорировать тот факт, что нет прототипа, но если при линковке найдет подходящий символ, то все слинкует. А вот будет ли работать — не известно, так как прототип неизвестен и может произойти ЧП со стеком. В данном случае нужно добавить #include <unistd.h>

ответ дан 19 апр 2013 в 19:17

KoVadim's user avatar

KoVadimKoVadim

112k6 золотых знаков92 серебряных знака159 бронзовых знаков

Студворк — интернет-сервис помощи студентам

Доброе время суток! Столкнулся с такой проблемой. Мне нужно считывать текстовые данные из консоли и обрабатывать их далее. Следующий код не компилируется:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
 
void main(int argc, char* args[])
{
    if(argc == 1)
    {
        char* loginBuf;
        printf("Input login: ");
        // gets_s(loginBuf, 100);
        gets(loginBuf);
        printf("LOGIN %s", loginBuf);
    }
    return;
}

Сообщение от компилятора:
client.c: В функции «main»:
client.c:36:3: предупреждение: неявная декларация функции «gets» [-Wimplicit-function-declaration]
gets(loginBuf);
^
/tmp/ccJw5VoU.o: In function `main’:
client.c: (.text+0x31): warning: the `gets’ function is dangerous and should not be used.

Пытался использовать gets_s, но ситуация аналогична:
client.c: В функции «main»:
client.c:35:3: предупреждение: неявная декларация функции «gets_s» [-Wimplicit-function-declaration]
gets_s(loginBuf, 100);
^
/tmp/ccNICvXH.o: In function `main’:
client.c: (.text+0x36): undefined reference to `gets_s’
collect2: ошибка: выполнение ld завершилось с кодом возврата 1

Насколько я понимаю, gets и gets_s содержатся в stdio.h, а он подключен.
Почему может выдаваться данная ошибка?

Компилятор gcc, ОС Fedora.
Спасибо за внимание.

> Судя по флагам в Makefile, исходник следует стандарту C99.

C99 — это стандарт языка и базовых библиотек, и popen/pclose в них не входят.

> То есть мне надо поставть ещё
> #define _XOPEN_SOURCE 600
> или 700?..

в данном конкретном случае — пофиг. как видно из мана, тебе необходимо определить либо _POSIX_C_SOURCE значением 2 или больше, либо определить любым целочисленным значением или без значений вовсе _XOPEN_SOURCE, _BSD_SOURCE или _SVID_SOURCE.

почитай на досуге man feature_test_macros.

arsi ★★★★★

(11.09.11 13:24:31 MSK)

  • Показать ответ
  • Ссылка

К современному С эта тема имеет отношение только в контексте вызова функции, объявленной без прототипа.

Современный язык С запрещает вызов необъявленных функций. Начиная с C99 все функции должны быть объявлены пред вызовом. Вызов необъявленной функции — это constraint violation, т.е. ошибка. Все остальное — самодеятельность вашего компилятора, к языку С никакого отношения не имеющая.

В устаревшем стандарте C89/90 вызов необъявленных функций разрешался. Компилятор пытался «угадать» тип функции на основе количества и типов передаваемых аргументов (типы аргументов после default argument promotions), а также подразумевал возвращаемое значение типа int.

short s = 0;
/* Вызов необъявленной функции */
foo(s, 5, 3.14f, "H");
/* Компилятор предполагает:
   int foo(int, int, double, char *) */

Современный С ведет себя по этой же схеме, если объявление функции сделано, но без прототипа (т.наз. «объявления в K&R стиле»). Угадывать тип возвращаемого значения больше не нужно, т.к. он явно присутствует в объявлении, а угадывание типов параметров делается по-старому. Объявления без прототипа являются deprecated.

Если «угаданный» тип функции несовместим с фактическим — поведение не определено. При попытке вызова variadic функции без предварительного объявления поведение не определено в любом случае.

Denisisk

1

27.02.2014, 21:15. Показов 4502. Ответов 1

Метки нет (Все метки)


Добрый день!Подскажите, пожалуйста, как избиваться от предупреждения:»неявная декларация функции «strlen»? Программа написана в среде Eclipse, ОС Ubuntu 12.04.
Условие:
Составить программу, определяющую, является ли заданная символьная строка с завершающим нулем палиндромом.

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <locale.h>
#include <stddef.h>
 
#define MaxLength 255 //Максимальная длина вводимой строки
 
//Данная функция принимает строку и размер строки.
//Затем сравнивает 1ый символ сначала строки и с конца. Если символы разные, то функция возвращает 1
//если функция проходит до середины строки и различных символов не находит, то возвращает 0.
int PolindromTest(char *StrB, size_t n)
{
    for (ptrdiff_t i=0;i<(n/2); i++)
        if (*(StrB+i) != *(StrB+n-i-1)) return 0;
    return 1;
}
 
//Данная функция принимает строку и обеспечивает ввод данных в эту строку из канала stdin.
//Если была введена строка нулевой длины, то возвращает 1
//Если была введена строка длиной более 255 символов бозвращает 2
//Если ввод был корректен, то возвращает, длину строки.
//Ошибка ввода-3.
size_t InputString(char *StrB)
{
    if (fgets(StrB,MaxLength+5,stdin)==NULL) return 3;
    //const char *Strin=StrB;
    size_t i=strlen(StrB);
    i--;
    if (i>MaxLength) return 2;
    if (i==0) return 1;
    StrB[i]='';
    return 0;
}
 
 
int main()
{
    setlocale (LC_ALL,"RUS");
    printf("Данная программа опредлеят, является ли заданная символьная строка палиндромом.nВведите строку, длиной не превышающей 256 знаков.n");
    char String[MaxLength];//В строке String будет храниться строка.
    size_t len=InputString(String); //Длина строки.
    if (len==1)
    {
        printf("Была введена строка нулевой длины");
        return 0;
    }
    else if (len==3)
    {
        printf ("Ошибка ввода.");
        return 0;
    }
    else if (len==2)
    {
        printf("Длина введенной строки превышает 256 символов");
        return 0;
    };
    int Polindrom=PolindromTest(String, len);
    if (Polindrom)
        printf("Yes");
    else printf("Строка не является полиндромом");
    return 0;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

uburuntu

95 / 95 / 58

Регистрация: 04.10.2012

Сообщений: 189

27.02.2014, 21:36

2

Вы забыли подключить string.h

C
1
#include <string.h>

Добавлено через 8 минут

Не по теме:

И определитесь уже «палиндром» или «полиндром» ;)

1

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

27.02.2014, 21:36

2

When your teacher calls up a student who is absent in the class, all students may yell «He isn’t here!»

Lets look at the warning:

warning: implicit declaration of function ‘Min’ is invalid in C99 [-Wimplicit-function-declaration]

This means, that you are trying to use Min without declaring it in your code, and that isn’t allowed.
It not an error, but a warning, which will cause a linker error eventually.

Here:

minVal = Min(x, y, z);

So, either you need to write a function called Min, or you need to replace Min with some function that you have already declared. For example,

void minVal (double x, double y, double z, double minVal)

Now, even if you change the call from Min to minVal, it won’t work. Because your code has a function called minVal and a variable with the same name. Thats chaotic. Make a habit to refrain declaring variables and function with a same name.

This function is returning void, and you are trying to determine the minimum of 3 inputs with double as data type, and assign the value to last variable passed as an argument. Doable, but not convenient as compared to returning a value, right?

When trying to find the minimum value from 3 inputs without touching the main.

I’d suggest this way:

#include <stdio.h>

double Min(double x, double y, double z)
{
    if (x<y && x<z)
        return x;
    else if (y<x && y<z)
        return y;
    else if (z<x && z<y)
        return z;
    else
        return 0.0;
}

int main(void)
{
    double x, y, z, minVal = 0.0;

    printf("Please enter three numeric values: ");
    scanf("%lf%lf%lf", &x, &y, &z);
    minVal = Min(x, y, z);
    printf("Min(%0.10f, %0.10f, %0.10f) = %0.10fn", x, y, z, minVal);

    return 0;
}

This code has following changes from what you had come up with:

  • Function renamed to Min from minVal. Note that usually it is preferred to use verbs/actions for function name, so that its easy to interpret what the function does. So, if I have the liberty to change main() function, I’ll use the name Get_minValue instead of Min in all the places (declaration and the function call).
  • Change the return type of Min to double, so that I can return the value rather than assigning it to an argument.

You can still make it better by getting rid of the minVal variable, I’ll let you figure that out :-)

Additionally, C99 is old, next time you compile your code, make sure you compile it with -std=c11 -pedantic-errors.

Here you can find more information on compiler options.

When your teacher calls up a student who is absent in the class, all students may yell «He isn’t here!»

Lets look at the warning:

warning: implicit declaration of function ‘Min’ is invalid in C99 [-Wimplicit-function-declaration]

This means, that you are trying to use Min without declaring it in your code, and that isn’t allowed.
It not an error, but a warning, which will cause a linker error eventually.

Here:

minVal = Min(x, y, z);

So, either you need to write a function called Min, or you need to replace Min with some function that you have already declared. For example,

void minVal (double x, double y, double z, double minVal)

Now, even if you change the call from Min to minVal, it won’t work. Because your code has a function called minVal and a variable with the same name. Thats chaotic. Make a habit to refrain declaring variables and function with a same name.

This function is returning void, and you are trying to determine the minimum of 3 inputs with double as data type, and assign the value to last variable passed as an argument. Doable, but not convenient as compared to returning a value, right?

When trying to find the minimum value from 3 inputs without touching the main.

I’d suggest this way:

#include <stdio.h>

double Min(double x, double y, double z)
{
    if (x<y && x<z)
        return x;
    else if (y<x && y<z)
        return y;
    else if (z<x && z<y)
        return z;
    else
        return 0.0;
}

int main(void)
{
    double x, y, z, minVal = 0.0;

    printf("Please enter three numeric values: ");
    scanf("%lf%lf%lf", &x, &y, &z);
    minVal = Min(x, y, z);
    printf("Min(%0.10f, %0.10f, %0.10f) = %0.10fn", x, y, z, minVal);

    return 0;
}

This code has following changes from what you had come up with:

  • Function renamed to Min from minVal. Note that usually it is preferred to use verbs/actions for function name, so that its easy to interpret what the function does. So, if I have the liberty to change main() function, I’ll use the name Get_minValue instead of Min in all the places (declaration and the function call).
  • Change the return type of Min to double, so that I can return the value rather than assigning it to an argument.

You can still make it better by getting rid of the minVal variable, I’ll let you figure that out :-)

Additionally, C99 is old, next time you compile your code, make sure you compile it with -std=c11 -pedantic-errors.

Here you can find more information on compiler options.

Вопрос:

Может кто-нибудь объяснить мне, почему следующие компиляции:

int main()
{
int a = mymethod(0);
}
int mymethod(int b)
{
return b;
}

но это не так:

int main()
{
mymethod(0);
}
void mymethod(int b)
{
return;
}

Я думал, что в C/С++ требуются форвардные объявления, но вот контрпример. Как неявные декларации работают в C?

Лучший ответ:

Я предполагаю, что когда вы говорите, что он не работает во втором примере кода, вы имеете в виду, что вы получаете ошибку времени компиляции.

Причина в том, что, когда есть объявление неявной функции, предполагается, что оно принимает фиксированное число аргументов и возвращает int. Тем не менее, mymethod() сначала неявно объявляется, а затем объявляется return void. Это ошибка, поскольку новое объявление не соответствует предыдущему (неявному) объявлению.

C90 (ANSI C89) допускает неявные декларации функций. Из раздела C89, раздел 3.3.2.2:

Если выражение, которое предшествует списку аргументов в скобках, вызов функции состоит только из идентификатора, и если нет для этого идентификатора видна декларация, идентификатор неявно объявляется точно так, как если бы в самом внутреннем блоке, содержащем вызов функции, декларация   

extern int  identifier();

появилась.

Однако это пособие было снято с C99 (и, следовательно, также запрещено в C11). С++ никогда не допускал неявных деклараций функций.

Ответ №1

Неявные объявления, генерируемые компилятором, предполагают, что возвращаемый тип функции int, что иногда не то, что вы хотите. Избегайте использования.

Обратите внимание, что неявные объявления работают только на C89, они удалены на C99. С++ тоже не поддерживает его.

Это можно подтвердить в стандарте C11 (ISO/IEC 9899: 201x).

В разделе C11 Forward перечислены все основные изменения в третьем издании (например, C11) и втором издании (то есть C99), один из которых:

Основные изменения во втором издании включали:

– удалить неявное объявление функции

Также в Обоснование для языков международного стандартного программирования C §6.5.2.2 Функциональные вызовы

Новая функция C99: правило для неявного объявления функций было удалено на C99. Эффект заключается в том, чтобы гарантировать получение диагностики, которая будет ловить дополнительную категорию ошибок программирования. После выдачи диагностики реализация может предпочесть неявное объявление и продолжить перевод, чтобы поддерживать существующие программы, которые использовали эту функцию.

Ответ №2

По умолчанию предполагается, что функция возвращает int. Итак, первая работала (к счастью), потому что это было так. В общем, это не так.

Ответ №3

Для неявной функции в C99 функция должна быть объявлена ​​до ее вызова. При объявлении напишите правильный прототип функций. Прототип объявления метода по умолчанию имеет тип возвращаемого значения “int”, поэтому он отлично работает (в первом случае вашего примера) с одним предупреждением (например, “неявное объявление функции недопустимо в c99” ).
Но во втором случае вы изменили прототип по умолчанию, поэтому вам нужно объявить его прототип.

Например:

//Function prototype declaration
void mymethod(int);

//Implementations
int main()
{
mymethod(0);
}

void mymethod(int b)
{
return;
}

Когда вы делаете свои #includes в main.c, поместите ссылку #include на файл, который содержит указанную функцию, вверху списка включения. например, скажем, что это main.c, а указанная функция находится в «SSD1306_LCD.h»

#include "SSD1306_LCD.h"    
#include "system.h"        #include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h>       // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h"  // This has the 'BYTE' type definition

Вышеупомянутое не приведет к возникновению ошибки «неявное объявление функции», но ниже будет —

#include "system.h"        
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h>       // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h"     // This has the 'BYTE' type definition
#include "SSD1306_LCD.h"    

Точно такой же список #include, только в другом порядке.

Что ж, для меня это сработало.

Comments

@pavlinux

vvv19xx

pushed a commit
that referenced
this issue

Jul 18, 2019

@gregkh

[ Upstream commit c5a94f434c82529afda290df3235e4d85873c5b4 ]

It was observed that a process blocked indefintely in
__fscache_read_or_alloc_page(), waiting for FSCACHE_COOKIE_LOOKING_UP
to be cleared via fscache_wait_for_deferred_lookup().

At this time, ->backing_objects was empty, which would normaly prevent
__fscache_read_or_alloc_page() from getting to the point of waiting.
This implies that ->backing_objects was cleared *after*
__fscache_read_or_alloc_page was was entered.

When an object is "killed" and then "dropped",
FSCACHE_COOKIE_LOOKING_UP is cleared in fscache_lookup_failure(), then
KILL_OBJECT and DROP_OBJECT are "called" and only in DROP_OBJECT is
->backing_objects cleared.  This leaves a window where
something else can set FSCACHE_COOKIE_LOOKING_UP and
__fscache_read_or_alloc_page() can start waiting, before
->backing_objects is cleared

There is some uncertainty in this analysis, but it seems to be fit the
observations.  Adding the wake in this patch will be handled correctly
by __fscache_read_or_alloc_page(), as it checks if ->backing_objects
is empty again, after waiting.

Customer which reported the hang, also report that the hang cannot be
reproduced with this fix.

The backtrace for the blocked process looked like:

PID: 29360  TASK: ffff881ff2ac0f80  CPU: 3   COMMAND: "zsh"
 #0 [ffff881ff43efbf8] schedule at ffffffff815e56f1
 #1 [ffff881ff43efc58] bit_wait at ffffffff815e64ed
 #2 [ffff881ff43efc68] __wait_on_bit at ffffffff815e61b8
 #3 [ffff881ff43efca0] out_of_line_wait_on_bit at ffffffff815e625e
 #4 [ffff881ff43efd08] fscache_wait_for_deferred_lookup at ffffffffa04f2e8f [fscache]
 #5 [ffff881ff43efd18] __fscache_read_or_alloc_page at ffffffffa04f2ffe [fscache]
 #6 [ffff881ff43efd58] __nfs_readpage_from_fscache at ffffffffa0679668 [nfs]
 #7 [ffff881ff43efd78] nfs_readpage at ffffffffa067092b [nfs]
 #8 [ffff881ff43efda0] generic_file_read_iter at ffffffff81187a73
 #9 [ffff881ff43efe50] nfs_file_read at ffffffffa066544b [nfs]
#10 [ffff881ff43efe70] __vfs_read at ffffffff811fc756
#11 [ffff881ff43efee8] vfs_read at ffffffff811fccfa
#12 [ffff881ff43eff18] sys_read at ffffffff811fda62
#13 [ffff881ff43eff50] entry_SYSCALL_64_fastpath at ffffffff815e986e

Signed-off-by: NeilBrown <neilb@suse.com>
Signed-off-by: David Howells <dhowells@redhat.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>

vvv19xx

pushed a commit
that referenced
this issue

Sep 25, 2019

@gregkh

[ Upstream commit 163d1c3d6f17556ed3c340d3789ea93be95d6c28 ]

Back in 2013 Hannes took care of most of such leaks in commit
bceaa90 ("inet: prevent leakage of uninitialized memory to user in recv syscalls")

But the bug in l2tp_ip6_recvmsg() has not been fixed.

syzbot report :

BUG: KMSAN: kernel-infoleak in _copy_to_user+0x16b/0x1f0 lib/usercopy.c:32
CPU: 1 PID: 10996 Comm: syz-executor362 Not tainted 5.0.0+ #11
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011
Call Trace:
 __dump_stack lib/dump_stack.c:77 [inline]
 dump_stack+0x173/0x1d0 lib/dump_stack.c:113
 kmsan_report+0x12e/0x2a0 mm/kmsan/kmsan.c:600
 kmsan_internal_check_memory+0x9f4/0xb10 mm/kmsan/kmsan.c:694
 kmsan_copy_to_user+0xab/0xc0 mm/kmsan/kmsan_hooks.c:601
 _copy_to_user+0x16b/0x1f0 lib/usercopy.c:32
 copy_to_user include/linux/uaccess.h:174 [inline]
 move_addr_to_user+0x311/0x570 net/socket.c:227
 ___sys_recvmsg+0xb65/0x1310 net/socket.c:2283
 do_recvmmsg+0x646/0x10c0 net/socket.c:2390
 __sys_recvmmsg net/socket.c:2469 [inline]
 __do_sys_recvmmsg net/socket.c:2492 [inline]
 __se_sys_recvmmsg+0x1d1/0x350 net/socket.c:2485
 __x64_sys_recvmmsg+0x62/0x80 net/socket.c:2485
 do_syscall_64+0xbc/0xf0 arch/x86/entry/common.c:291
 entry_SYSCALL_64_after_hwframe+0x63/0xe7
RIP: 0033:0x445819
Code: e8 6c b6 02 00 48 83 c4 18 c3 0f 1f 80 00 00 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 0f 83 2b 12 fc ff c3 66 2e 0f 1f 84 00 00 00 00
RSP: 002b:00007f64453eddb8 EFLAGS: 00000246 ORIG_RAX: 000000000000012b
RAX: ffffffffffffffda RBX: 00000000006dac28 RCX: 0000000000445819
RDX: 0000000000000005 RSI: 0000000020002f80 RDI: 0000000000000003
RBP: 00000000006dac20 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00000000006dac2c
R13: 00007ffeba8f87af R14: 00007f64453ee9c0 R15: 20c49ba5e353f7cf

Local variable description: ----addr@___sys_recvmsg
Variable was created at:
 ___sys_recvmsg+0xf6/0x1310 net/socket.c:2244
 do_recvmmsg+0x646/0x10c0 net/socket.c:2390

Bytes 0-31 of 32 are uninitialized
Memory access of size 32 starts at ffff8880ae62fbb0
Data copied to user address 0000000020000000

Fixes: a32e0ee ("l2tp: introduce L2TPv3 IP encapsulation support for IPv6")
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reported-by: syzbot <syzkaller@googlegroups.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

vvv19xx

pushed a commit
that referenced
this issue

Sep 25, 2019

@gregkh

…ll_sock().

[ Upstream commit cb66ddd156203daefb8d71158036b27b0e2caf63 ]

When it is to cleanup net namespace, rds_tcp_exit_net() will call
rds_tcp_kill_sock(), if t_sock is NULL, it will not call
rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free
connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in
net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect()
and reference 'net' which has already been freed.

In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before
sock->ops->connect, but if connect() is failed, it will call
rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always
failed, rds_connect_worker() will try to reconnect all the time, so
rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the
connections.

Therefore, the condition !tc->t_sock is not needed if it is going to do
cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always
NULL, and there is on other path to cancel cp_conn_w and free
connection. So this patch is to fix this.

rds_tcp_kill_sock():
...
if (net != c_net || !tc->t_sock)
...
Acked-by: Santosh Shilimkar <santosh.shilimkar@oracle.com>

==================================================================
BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28
net/ipv4/af_inet.c:340
Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721

CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11
Hardware name: linux,dummy-virt (DT)
Workqueue: krdsd rds_connect_worker
Call trace:
 dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53
 show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152
 __dump_stack lib/dump_stack.c:77 [inline]
 dump_stack+0x120/0x188 lib/dump_stack.c:113
 print_address_description+0x68/0x278 mm/kasan/report.c:253
 kasan_report_error mm/kasan/report.c:351 [inline]
 kasan_report+0x21c/0x348 mm/kasan/report.c:409
 __asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429
 inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340
 __sock_create+0x4f8/0x770 net/socket.c:1276
 sock_create_kern+0x50/0x68 net/socket.c:1322
 rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114
 rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175
 process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
 worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
 kthread+0x2f0/0x378 kernel/kthread.c:255
 ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117

Allocated by task 687:
 save_stack mm/kasan/kasan.c:448 [inline]
 set_track mm/kasan/kasan.c:460 [inline]
 kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553
 kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490
 slab_post_alloc_hook mm/slab.h:444 [inline]
 slab_alloc_node mm/slub.c:2705 [inline]
 slab_alloc mm/slub.c:2713 [inline]
 kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718
 kmem_cache_zalloc include/linux/slab.h:697 [inline]
 net_alloc net/core/net_namespace.c:384 [inline]
 copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424
 create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107
 unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206
 ksys_unshare+0x340/0x628 kernel/fork.c:2577
 __do_sys_unshare kernel/fork.c:2645 [inline]
 __se_sys_unshare kernel/fork.c:2643 [inline]
 __arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643
 __invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
 invoke_syscall arch/arm64/kernel/syscall.c:47 [inline]
 el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83
 el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129
 el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960

Freed by task 264:
 save_stack mm/kasan/kasan.c:448 [inline]
 set_track mm/kasan/kasan.c:460 [inline]
 __kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521
 kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528
 slab_free_hook mm/slub.c:1370 [inline]
 slab_free_freelist_hook mm/slub.c:1397 [inline]
 slab_free mm/slub.c:2952 [inline]
 kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968
 net_free net/core/net_namespace.c:400 [inline]
 net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407
 net_drop_ns net/core/net_namespace.c:406 [inline]
 cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569
 process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
 worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
 kthread+0x2f0/0x378 kernel/kthread.c:255
 ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117

The buggy address belongs to the object at ffff8003496a3f80
 which belongs to the cache net_namespace of size 7872
The buggy address is located 1796 bytes inside of
 7872-byte region [ffff8003496a3f80, ffff8003496a5e40)
The buggy address belongs to the page:
page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000
index:0x0 compound_mapcount: 0
flags: 0xffffe0000008100(slab|head)
raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000
raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected

Memory state around the buggy address:
 ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
 ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                   ^
 ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
 ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================

Fixes: 467fa15("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.")
Reported-by: Hulk Robot <hulkci@huawei.com>
Signed-off-by: Mao Wenan <maowenan@huawei.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

vvv19xx

pushed a commit
that referenced
this issue

Sep 25, 2019

@acmel

@gregkh

[ Upstream commit 42dfa451d825a2ad15793c476f73e7bbc0f9d312 ]

Using gcc's ASan, Changbin reports:

  =================================================================
  ==7494==ERROR: LeakSanitizer: detected memory leaks

  Direct leak of 48 byte(s) in 1 object(s) allocated from:
      #0 0x7f0333a89138 in calloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xee138)
      #1 0x5625e5330a5e in zalloc util/util.h:23
      #2 0x5625e5330a9b in perf_counts__new util/counts.c:10
      #3 0x5625e5330ca0 in perf_evsel__alloc_counts util/counts.c:47
      #4 0x5625e520d8e5 in __perf_evsel__read_on_cpu util/evsel.c:1505
      #5 0x5625e517a985 in perf_evsel__read_on_cpu /home/work/linux/tools/perf/util/evsel.h:347
      #6 0x5625e517ad1a in test__openat_syscall_event tests/openat-syscall.c:47
      #7 0x5625e51528e6 in run_test tests/builtin-test.c:358
      #8 0x5625e5152baf in test_and_print tests/builtin-test.c:388
      #9 0x5625e51543fe in __cmd_test tests/builtin-test.c:583
      #10 0x5625e515572f in cmd_test tests/builtin-test.c:722
      #11 0x5625e51c3fb8 in run_builtin /home/changbin/work/linux/tools/perf/perf.c:302
      #12 0x5625e51c44f7 in handle_internal_command /home/changbin/work/linux/tools/perf/perf.c:354
      #13 0x5625e51c48fb in run_argv /home/changbin/work/linux/tools/perf/perf.c:398
      #14 0x5625e51c5069 in main /home/changbin/work/linux/tools/perf/perf.c:520
      #15 0x7f033214d09a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2409a)

  Indirect leak of 72 byte(s) in 1 object(s) allocated from:
      #0 0x7f0333a89138 in calloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xee138)
      #1 0x5625e532560d in zalloc util/util.h:23
      #2 0x5625e532566b in xyarray__new util/xyarray.c:10
      #3 0x5625e5330aba in perf_counts__new util/counts.c:15
      #4 0x5625e5330ca0 in perf_evsel__alloc_counts util/counts.c:47
      #5 0x5625e520d8e5 in __perf_evsel__read_on_cpu util/evsel.c:1505
      #6 0x5625e517a985 in perf_evsel__read_on_cpu /home/work/linux/tools/perf/util/evsel.h:347
      #7 0x5625e517ad1a in test__openat_syscall_event tests/openat-syscall.c:47
      #8 0x5625e51528e6 in run_test tests/builtin-test.c:358
      #9 0x5625e5152baf in test_and_print tests/builtin-test.c:388
      #10 0x5625e51543fe in __cmd_test tests/builtin-test.c:583
      #11 0x5625e515572f in cmd_test tests/builtin-test.c:722
      #12 0x5625e51c3fb8 in run_builtin /home/changbin/work/linux/tools/perf/perf.c:302
      #13 0x5625e51c44f7 in handle_internal_command /home/changbin/work/linux/tools/perf/perf.c:354
      #14 0x5625e51c48fb in run_argv /home/changbin/work/linux/tools/perf/perf.c:398
      #15 0x5625e51c5069 in main /home/changbin/work/linux/tools/perf/perf.c:520
      #16 0x7f033214d09a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2409a)

His patch took care of evsel->prev_raw_counts, but the above backtraces
are about evsel->counts, so fix that instead.

Reported-by: Changbin Du <changbin.du@gmail.com>
Cc: Alexei Starovoitov <ast@kernel.org>
Cc: Daniel Borkmann <daniel@iogearbox.net>
Cc: Jiri Olsa <jolsa@kernel.org>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Steven Rostedt (VMware) <rostedt@goodmis.org>
Link: https://lkml.kernel.org/n/tip-hd1x13g59f0nuhe4anxhsmfp@git.kernel.org
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>

vvv19xx

pushed a commit
that referenced
this issue

Sep 25, 2019

@changbindu

@gregkh

…_event_on_all_cpus test

[ Upstream commit 93faa52e8371f0291ee1ff4994edae2b336b6233 ]

  =================================================================
  ==7497==ERROR: LeakSanitizer: detected memory leaks

  Direct leak of 40 byte(s) in 1 object(s) allocated from:
      #0 0x7f0333a88f30 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xedf30)
      #1 0x5625e5326213 in cpu_map__trim_new util/cpumap.c:45
      #2 0x5625e5326703 in cpu_map__read util/cpumap.c:103
      #3 0x5625e53267ef in cpu_map__read_all_cpu_map util/cpumap.c:120
      #4 0x5625e5326915 in cpu_map__new util/cpumap.c:135
      #5 0x5625e517b355 in test__openat_syscall_event_on_all_cpus tests/openat-syscall-all-cpus.c:36
      #6 0x5625e51528e6 in run_test tests/builtin-test.c:358
      #7 0x5625e5152baf in test_and_print tests/builtin-test.c:388
      #8 0x5625e51543fe in __cmd_test tests/builtin-test.c:583
      #9 0x5625e515572f in cmd_test tests/builtin-test.c:722
      #10 0x5625e51c3fb8 in run_builtin /home/changbin/work/linux/tools/perf/perf.c:302
      #11 0x5625e51c44f7 in handle_internal_command /home/changbin/work/linux/tools/perf/perf.c:354
      #12 0x5625e51c48fb in run_argv /home/changbin/work/linux/tools/perf/perf.c:398
      #13 0x5625e51c5069 in main /home/changbin/work/linux/tools/perf/perf.c:520
      #14 0x7f033214d09a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2409a)

Signed-off-by: Changbin Du <changbin.du@gmail.com>
Reviewed-by: Jiri Olsa <jolsa@kernel.org>
Cc: Alexei Starovoitov <ast@kernel.org>
Cc: Daniel Borkmann <daniel@iogearbox.net>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Steven Rostedt (VMware) <rostedt@goodmis.org>
Fixes: f30a79b ("perf tools: Add reference counting for cpu_map object")
Link: http://lkml.kernel.org/r/20190316080556.3075-15-changbin.du@gmail.com
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>

vvv19xx

pushed a commit
that referenced
this issue

Sep 25, 2019

@changbindu

@gregkh

[ Upstream commit d982b33133284fa7efa0e52ae06b88f9be3ea764 ]

  =================================================================
  ==20875==ERROR: LeakSanitizer: detected memory leaks

  Direct leak of 1160 byte(s) in 1 object(s) allocated from:
      #0 0x7f1b6fc84138 in calloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xee138)
      #1 0x55bd50005599 in zalloc util/util.h:23
      #2 0x55bd500068f5 in perf_evsel__newtp_idx util/evsel.c:327
      #3 0x55bd4ff810fc in perf_evsel__newtp /home/work/linux/tools/perf/util/evsel.h:216
      #4 0x55bd4ff81608 in test__perf_evsel__tp_sched_test tests/evsel-tp-sched.c:69
      #5 0x55bd4ff528e6 in run_test tests/builtin-test.c:358
      #6 0x55bd4ff52baf in test_and_print tests/builtin-test.c:388
      #7 0x55bd4ff543fe in __cmd_test tests/builtin-test.c:583
      #8 0x55bd4ff5572f in cmd_test tests/builtin-test.c:722
      #9 0x55bd4ffc4087 in run_builtin /home/changbin/work/linux/tools/perf/perf.c:302
      #10 0x55bd4ffc45c6 in handle_internal_command /home/changbin/work/linux/tools/perf/perf.c:354
      #11 0x55bd4ffc49ca in run_argv /home/changbin/work/linux/tools/perf/perf.c:398
      #12 0x55bd4ffc5138 in main /home/changbin/work/linux/tools/perf/perf.c:520
      #13 0x7f1b6e34809a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2409a)

  Indirect leak of 19 byte(s) in 1 object(s) allocated from:
      #0 0x7f1b6fc83f30 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xedf30)
      #1 0x7f1b6e3ac30f in vasprintf (/lib/x86_64-linux-gnu/libc.so.6+0x8830f)

Signed-off-by: Changbin Du <changbin.du@gmail.com>
Reviewed-by: Jiri Olsa <jolsa@kernel.org>
Cc: Alexei Starovoitov <ast@kernel.org>
Cc: Daniel Borkmann <daniel@iogearbox.net>
Cc: Namhyung Kim <namhyung@kernel.org>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Steven Rostedt (VMware) <rostedt@goodmis.org>
Fixes: 6a6cd11 ("perf test: Add test for the sched tracepoint format fields")
Link: http://lkml.kernel.org/r/20190316080556.3075-17-changbin.du@gmail.com
Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>

  • Ошибка нечем открыть apk что значит
  • Ошибка нехватка электропитания usb порта windows 10
  • Ошибка нехватка разделяемой памяти
  • Ошибка нехватка питания usb порта
  • Ошибка нехватка памяти при обновлении 1с